babylon.no-module.max.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333983349833598336983379833898339
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  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 if (otherMesh.subMeshes) {
  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. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * 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)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * 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)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  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. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. _this.skipOnPointerObservable = false;
  1342. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1343. return _this;
  1344. }
  1345. return PointerInfoPre;
  1346. }(PointerInfoBase));
  1347. BABYLON.PointerInfoPre = PointerInfoPre;
  1348. /**
  1349. * This type contains all the data related to a pointer event in Babylon.js.
  1350. * 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.
  1351. */
  1352. var PointerInfo = /** @class */ (function (_super) {
  1353. __extends(PointerInfo, _super);
  1354. function PointerInfo(type, event, pickInfo) {
  1355. var _this = _super.call(this, type, event) || this;
  1356. _this.pickInfo = pickInfo;
  1357. return _this;
  1358. }
  1359. return PointerInfo;
  1360. }(PointerInfoBase));
  1361. BABYLON.PointerInfo = PointerInfo;
  1362. })(BABYLON || (BABYLON = {}));
  1363. //# sourceMappingURL=babylon.pointerEvents.js.map
  1364. var BABYLON;
  1365. (function (BABYLON) {
  1366. BABYLON.ToGammaSpace = 1 / 2.2;
  1367. BABYLON.ToLinearSpace = 2.2;
  1368. BABYLON.Epsilon = 0.001;
  1369. /**
  1370. * Class used to hold a RBG color
  1371. */
  1372. var Color3 = /** @class */ (function () {
  1373. /**
  1374. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1375. * @param r defines the red component (between 0 and 1, default is 0)
  1376. * @param g defines the green component (between 0 and 1, default is 0)
  1377. * @param b defines the blue component (between 0 and 1, default is 0)
  1378. */
  1379. function Color3(
  1380. /**
  1381. * Defines the red component (between 0 and 1, default is 0)
  1382. */
  1383. r,
  1384. /**
  1385. * Defines the green component (between 0 and 1, default is 0)
  1386. */
  1387. g,
  1388. /**
  1389. * Defines the blue component (between 0 and 1, default is 0)
  1390. */
  1391. b) {
  1392. if (r === void 0) { r = 0; }
  1393. if (g === void 0) { g = 0; }
  1394. if (b === void 0) { b = 0; }
  1395. this.r = r;
  1396. this.g = g;
  1397. this.b = b;
  1398. }
  1399. /**
  1400. * Creates a string with the Color3 current values
  1401. * @returns the string representation of the Color3 object
  1402. */
  1403. Color3.prototype.toString = function () {
  1404. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1405. };
  1406. /**
  1407. * Returns the string "Color3"
  1408. * @returns "Color3"
  1409. */
  1410. Color3.prototype.getClassName = function () {
  1411. return "Color3";
  1412. };
  1413. /**
  1414. * Compute the Color3 hash code
  1415. * @returns an unique number that can be used to hash Color3 objects
  1416. */
  1417. Color3.prototype.getHashCode = function () {
  1418. var hash = this.r || 0;
  1419. hash = (hash * 397) ^ (this.g || 0);
  1420. hash = (hash * 397) ^ (this.b || 0);
  1421. return hash;
  1422. };
  1423. // Operators
  1424. /**
  1425. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1426. * @param array defines the array where to store the r,g,b components
  1427. * @param index defines an optional index in the target array to define where to start storing values
  1428. * @returns the current Color3 object
  1429. */
  1430. Color3.prototype.toArray = function (array, index) {
  1431. if (index === undefined) {
  1432. index = 0;
  1433. }
  1434. array[index] = this.r;
  1435. array[index + 1] = this.g;
  1436. array[index + 2] = this.b;
  1437. return this;
  1438. };
  1439. /**
  1440. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1441. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1442. * @returns a new {BABYLON.Color4} object
  1443. */
  1444. Color3.prototype.toColor4 = function (alpha) {
  1445. if (alpha === void 0) { alpha = 1; }
  1446. return new Color4(this.r, this.g, this.b, alpha);
  1447. };
  1448. /**
  1449. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1450. * @returns the new array
  1451. */
  1452. Color3.prototype.asArray = function () {
  1453. var result = new Array();
  1454. this.toArray(result, 0);
  1455. return result;
  1456. };
  1457. /**
  1458. * Returns the luminance value
  1459. * @returns a float value
  1460. */
  1461. Color3.prototype.toLuminance = function () {
  1462. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1463. };
  1464. /**
  1465. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1466. * @param otherColor defines the second operand
  1467. * @returns the new Color3 object
  1468. */
  1469. Color3.prototype.multiply = function (otherColor) {
  1470. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1471. };
  1472. /**
  1473. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1474. * @param otherColor defines the second operand
  1475. * @param result defines the Color3 object where to store the result
  1476. * @returns the current Color3
  1477. */
  1478. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1479. result.r = this.r * otherColor.r;
  1480. result.g = this.g * otherColor.g;
  1481. result.b = this.b * otherColor.b;
  1482. return this;
  1483. };
  1484. /**
  1485. * Determines equality between Color3 objects
  1486. * @param otherColor defines the second operand
  1487. * @returns true if the rgb values are equal to the given ones
  1488. */
  1489. Color3.prototype.equals = function (otherColor) {
  1490. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1491. };
  1492. /**
  1493. * Determines equality between the current Color3 object and a set of r,b,g values
  1494. * @param r defines the red component to check
  1495. * @param g defines the green component to check
  1496. * @param b defines the blue component to check
  1497. * @returns true if the rgb values are equal to the given ones
  1498. */
  1499. Color3.prototype.equalsFloats = function (r, g, b) {
  1500. return this.r === r && this.g === g && this.b === b;
  1501. };
  1502. /**
  1503. * Multiplies in place each rgb value by scale
  1504. * @param scale defines the scaling factor
  1505. * @returns the updated Color3
  1506. */
  1507. Color3.prototype.scale = function (scale) {
  1508. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1509. };
  1510. /**
  1511. * Multiplies the rgb values by scale and stores the result into "result"
  1512. * @param scale defines the scaling factor
  1513. * @param result defines the Color3 object where to store the result
  1514. * @returns the unmodified current Color3
  1515. */
  1516. Color3.prototype.scaleToRef = function (scale, result) {
  1517. result.r = this.r * scale;
  1518. result.g = this.g * scale;
  1519. result.b = this.b * scale;
  1520. return this;
  1521. };
  1522. /**
  1523. * Scale the current Color3 values by a factor and add the result to a given Color3
  1524. * @param scale defines the scale factor
  1525. * @param result defines color to store the result into
  1526. * @returns the unmodified current Color3
  1527. */
  1528. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1529. result.r += this.r * scale;
  1530. result.g += this.g * scale;
  1531. result.b += this.b * scale;
  1532. return this;
  1533. };
  1534. /**
  1535. * Clamps the rgb values by the min and max values and stores the result into "result"
  1536. * @param min defines minimum clamping value (default is 0)
  1537. * @param max defines maximum clamping value (default is 1)
  1538. * @param result defines color to store the result into
  1539. * @returns the original Color3
  1540. */
  1541. Color3.prototype.clampToRef = function (min, max, result) {
  1542. if (min === void 0) { min = 0; }
  1543. if (max === void 0) { max = 1; }
  1544. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1545. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1546. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1547. return this;
  1548. };
  1549. /**
  1550. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1551. * @param otherColor defines the second operand
  1552. * @returns the new Color3
  1553. */
  1554. Color3.prototype.add = function (otherColor) {
  1555. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1556. };
  1557. /**
  1558. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1559. * @param otherColor defines the second operand
  1560. * @param result defines Color3 object to store the result into
  1561. * @returns the unmodified current Color3
  1562. */
  1563. Color3.prototype.addToRef = function (otherColor, result) {
  1564. result.r = this.r + otherColor.r;
  1565. result.g = this.g + otherColor.g;
  1566. result.b = this.b + otherColor.b;
  1567. return this;
  1568. };
  1569. /**
  1570. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3
  1573. */
  1574. Color3.prototype.subtract = function (otherColor) {
  1575. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1576. };
  1577. /**
  1578. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines Color3 object to store the result into
  1581. * @returns the unmodified current Color3
  1582. */
  1583. Color3.prototype.subtractToRef = function (otherColor, result) {
  1584. result.r = this.r - otherColor.r;
  1585. result.g = this.g - otherColor.g;
  1586. result.b = this.b - otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Copy the current object
  1591. * @returns a new Color3 copied the current one
  1592. */
  1593. Color3.prototype.clone = function () {
  1594. return new Color3(this.r, this.g, this.b);
  1595. };
  1596. /**
  1597. * Copies the rgb values from the source in the current Color3
  1598. * @param source defines the source Color3 object
  1599. * @returns the updated Color3 object
  1600. */
  1601. Color3.prototype.copyFrom = function (source) {
  1602. this.r = source.r;
  1603. this.g = source.g;
  1604. this.b = source.b;
  1605. return this;
  1606. };
  1607. /**
  1608. * Updates the Color3 rgb values from the given floats
  1609. * @param r defines the red component to read from
  1610. * @param g defines the green component to read from
  1611. * @param b defines the blue component to read from
  1612. * @returns the current Color3 object
  1613. */
  1614. Color3.prototype.copyFromFloats = function (r, g, b) {
  1615. this.r = r;
  1616. this.g = g;
  1617. this.b = b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Updates the Color3 rgb values from the given floats
  1622. * @param r defines the red component to read from
  1623. * @param g defines the green component to read from
  1624. * @param b defines the blue component to read from
  1625. * @returns the current Color3 object
  1626. */
  1627. Color3.prototype.set = function (r, g, b) {
  1628. return this.copyFromFloats(r, g, b);
  1629. };
  1630. /**
  1631. * Compute the Color3 hexadecimal code as a string
  1632. * @returns a string containing the hexadecimal representation of the Color3 object
  1633. */
  1634. Color3.prototype.toHexString = function () {
  1635. var intR = (this.r * 255) | 0;
  1636. var intG = (this.g * 255) | 0;
  1637. var intB = (this.b * 255) | 0;
  1638. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1639. };
  1640. /**
  1641. * Computes a new Color3 converted from the current one to linear space
  1642. * @returns a new Color3 object
  1643. */
  1644. Color3.prototype.toLinearSpace = function () {
  1645. var convertedColor = new Color3();
  1646. this.toLinearSpaceToRef(convertedColor);
  1647. return convertedColor;
  1648. };
  1649. /**
  1650. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1651. * @param convertedColor defines the Color3 object where to store the linear space version
  1652. * @returns the unmodified Color3
  1653. */
  1654. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1655. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1656. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1657. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1658. return this;
  1659. };
  1660. /**
  1661. * Computes a new Color3 converted from the current one to gamma space
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.prototype.toGammaSpace = function () {
  1665. var convertedColor = new Color3();
  1666. this.toGammaSpaceToRef(convertedColor);
  1667. return convertedColor;
  1668. };
  1669. /**
  1670. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1671. * @param convertedColor defines the Color3 object where to store the gamma space version
  1672. * @returns the unmodified Color3
  1673. */
  1674. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1675. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1676. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1677. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1678. return this;
  1679. };
  1680. // Statics
  1681. /**
  1682. * Creates a new Color3 from the string containing valid hexadecimal values
  1683. * @param hex defines a string containing valid hexadecimal values
  1684. * @returns a new Color3 object
  1685. */
  1686. Color3.FromHexString = function (hex) {
  1687. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1688. return new Color3(0, 0, 0);
  1689. }
  1690. var r = parseInt(hex.substring(1, 3), 16);
  1691. var g = parseInt(hex.substring(3, 5), 16);
  1692. var b = parseInt(hex.substring(5, 7), 16);
  1693. return Color3.FromInts(r, g, b);
  1694. };
  1695. /**
  1696. * Creates a new Vector3 from the starting index of the given array
  1697. * @param array defines the source array
  1698. * @param offset defines an offset in the source array
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.FromArray = function (array, offset) {
  1702. if (offset === void 0) { offset = 0; }
  1703. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1704. };
  1705. /**
  1706. * Creates a new Color3 from integer values (< 256)
  1707. * @param r defines the red component to read from (value between 0 and 255)
  1708. * @param g defines the green component to read from (value between 0 and 255)
  1709. * @param b defines the blue component to read from (value between 0 and 255)
  1710. * @returns a new Color3 object
  1711. */
  1712. Color3.FromInts = function (r, g, b) {
  1713. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1714. };
  1715. /**
  1716. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1717. * @param start defines the start Color3 value
  1718. * @param end defines the end Color3 value
  1719. * @param amount defines the gradient value between start and end
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.Lerp = function (start, end, amount) {
  1723. var r = start.r + ((end.r - start.r) * amount);
  1724. var g = start.g + ((end.g - start.g) * amount);
  1725. var b = start.b + ((end.b - start.b) * amount);
  1726. return new Color3(r, g, b);
  1727. };
  1728. /**
  1729. * Returns a Color3 value containing a red color
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.Red = function () { return new Color3(1, 0, 0); };
  1733. /**
  1734. * Returns a Color3 value containing a green color
  1735. * @returns a new Color3 object
  1736. */
  1737. Color3.Green = function () { return new Color3(0, 1, 0); };
  1738. /**
  1739. * Returns a Color3 value containing a blue color
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1743. /**
  1744. * Returns a Color3 value containing a black color
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.Black = function () { return new Color3(0, 0, 0); };
  1748. /**
  1749. * Returns a Color3 value containing a white color
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.White = function () { return new Color3(1, 1, 1); };
  1753. /**
  1754. * Returns a Color3 value containing a purple color
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1758. /**
  1759. * Returns a Color3 value containing a magenta color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1763. /**
  1764. * Returns a Color3 value containing a yellow color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a gray color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1773. /**
  1774. * Returns a Color3 value containing a teal color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1778. /**
  1779. * Returns a Color3 value containing a random color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1783. return Color3;
  1784. }());
  1785. BABYLON.Color3 = Color3;
  1786. /**
  1787. * Class used to hold a RBGA color
  1788. */
  1789. var Color4 = /** @class */ (function () {
  1790. /**
  1791. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1792. * @param r defines the red component (between 0 and 1, default is 0)
  1793. * @param g defines the green component (between 0 and 1, default is 0)
  1794. * @param b defines the blue component (between 0 and 1, default is 0)
  1795. * @param a defines the alpha component (between 0 and 1, default is 1)
  1796. */
  1797. function Color4(
  1798. /**
  1799. * Defines the red component (between 0 and 1, default is 0)
  1800. */
  1801. r,
  1802. /**
  1803. * Defines the green component (between 0 and 1, default is 0)
  1804. */
  1805. g,
  1806. /**
  1807. * Defines the blue component (between 0 and 1, default is 0)
  1808. */
  1809. b,
  1810. /**
  1811. * Defines the alpha component (between 0 and 1, default is 1)
  1812. */
  1813. a) {
  1814. if (r === void 0) { r = 0; }
  1815. if (g === void 0) { g = 0; }
  1816. if (b === void 0) { b = 0; }
  1817. if (a === void 0) { a = 1; }
  1818. this.r = r;
  1819. this.g = g;
  1820. this.b = b;
  1821. this.a = a;
  1822. }
  1823. // Operators
  1824. /**
  1825. * Adds in place the given Color4 values to the current Color4 object
  1826. * @param right defines the second operand
  1827. * @returns the current updated Color4 object
  1828. */
  1829. Color4.prototype.addInPlace = function (right) {
  1830. this.r += right.r;
  1831. this.g += right.g;
  1832. this.b += right.b;
  1833. this.a += right.a;
  1834. return this;
  1835. };
  1836. /**
  1837. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1838. * @returns the new array
  1839. */
  1840. Color4.prototype.asArray = function () {
  1841. var result = new Array();
  1842. this.toArray(result, 0);
  1843. return result;
  1844. };
  1845. /**
  1846. * Stores from the starting index in the given array the Color4 successive values
  1847. * @param array defines the array where to store the r,g,b components
  1848. * @param index defines an optional index in the target array to define where to start storing values
  1849. * @returns the current Color4 object
  1850. */
  1851. Color4.prototype.toArray = function (array, index) {
  1852. if (index === undefined) {
  1853. index = 0;
  1854. }
  1855. array[index] = this.r;
  1856. array[index + 1] = this.g;
  1857. array[index + 2] = this.b;
  1858. array[index + 3] = this.a;
  1859. return this;
  1860. };
  1861. /**
  1862. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1863. * @param right defines the second operand
  1864. * @returns a new Color4 object
  1865. */
  1866. Color4.prototype.add = function (right) {
  1867. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1868. };
  1869. /**
  1870. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1871. * @param right defines the second operand
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.subtract = function (right) {
  1875. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1876. };
  1877. /**
  1878. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1879. * @param right defines the second operand
  1880. * @param result defines the Color4 object where to store the result
  1881. * @returns the current Color4 object
  1882. */
  1883. Color4.prototype.subtractToRef = function (right, result) {
  1884. result.r = this.r - right.r;
  1885. result.g = this.g - right.g;
  1886. result.b = this.b - right.b;
  1887. result.a = this.a - right.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new Color4 with the current Color4 values multiplied by scale
  1892. * @param scale defines the scaling factor to apply
  1893. * @returns a new Color4 object
  1894. */
  1895. Color4.prototype.scale = function (scale) {
  1896. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1897. };
  1898. /**
  1899. * Multiplies the current Color4 values by scale and stores the result in "result"
  1900. * @param scale defines the scaling factor to apply
  1901. * @param result defines the Color4 object where to store the result
  1902. * @returns the current unmodified Color4
  1903. */
  1904. Color4.prototype.scaleToRef = function (scale, result) {
  1905. result.r = this.r * scale;
  1906. result.g = this.g * scale;
  1907. result.b = this.b * scale;
  1908. result.a = this.a * scale;
  1909. return this;
  1910. };
  1911. /**
  1912. * Scale the current Color4 values by a factor and add the result to a given Color4
  1913. * @param scale defines the scale factor
  1914. * @param result defines the Color4 object where to store the result
  1915. * @returns the unmodified current Color4
  1916. */
  1917. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1918. result.r += this.r * scale;
  1919. result.g += this.g * scale;
  1920. result.b += this.b * scale;
  1921. result.a += this.a * scale;
  1922. return this;
  1923. };
  1924. /**
  1925. * Clamps the rgb values by the min and max values and stores the result into "result"
  1926. * @param min defines minimum clamping value (default is 0)
  1927. * @param max defines maximum clamping value (default is 1)
  1928. * @param result defines color to store the result into.
  1929. * @returns the cuurent Color4
  1930. */
  1931. Color4.prototype.clampToRef = function (min, max, result) {
  1932. if (min === void 0) { min = 0; }
  1933. if (max === void 0) { max = 1; }
  1934. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1935. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1936. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1937. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1938. return this;
  1939. };
  1940. /**
  1941. * Multipy an Color4 value by another and return a new Color4 object
  1942. * @param color defines the Color4 value to multiply by
  1943. * @returns a new Color4 object
  1944. */
  1945. Color4.prototype.multiply = function (color) {
  1946. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1947. };
  1948. /**
  1949. * Multipy a Color4 value by another and push the result in a reference value
  1950. * @param color defines the Color4 value to multiply by
  1951. * @param result defines the Color4 to fill the result in
  1952. * @returns the result Color4
  1953. */
  1954. Color4.prototype.multiplyToRef = function (color, result) {
  1955. result.r = this.r * color.r;
  1956. result.g = this.g * color.g;
  1957. result.b = this.b * color.b;
  1958. result.a = this.a * color.a;
  1959. return result;
  1960. };
  1961. /**
  1962. * Creates a string with the Color4 current values
  1963. * @returns the string representation of the Color4 object
  1964. */
  1965. Color4.prototype.toString = function () {
  1966. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1967. };
  1968. /**
  1969. * Returns the string "Color4"
  1970. * @returns "Color4"
  1971. */
  1972. Color4.prototype.getClassName = function () {
  1973. return "Color4";
  1974. };
  1975. /**
  1976. * Compute the Color4 hash code
  1977. * @returns an unique number that can be used to hash Color4 objects
  1978. */
  1979. Color4.prototype.getHashCode = function () {
  1980. var hash = this.r || 0;
  1981. hash = (hash * 397) ^ (this.g || 0);
  1982. hash = (hash * 397) ^ (this.b || 0);
  1983. hash = (hash * 397) ^ (this.a || 0);
  1984. return hash;
  1985. };
  1986. /**
  1987. * Creates a new Color4 copied from the current one
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.clone = function () {
  1991. return new Color4(this.r, this.g, this.b, this.a);
  1992. };
  1993. /**
  1994. * Copies the given Color4 values into the current one
  1995. * @param source defines the source Color4 object
  1996. * @returns the current updated Color4 object
  1997. */
  1998. Color4.prototype.copyFrom = function (source) {
  1999. this.r = source.r;
  2000. this.g = source.g;
  2001. this.b = source.b;
  2002. this.a = source.a;
  2003. return this;
  2004. };
  2005. /**
  2006. * Copies the given float values into the current one
  2007. * @param r defines the red component to read from
  2008. * @param g defines the green component to read from
  2009. * @param b defines the blue component to read from
  2010. * @param a defines the alpha component to read from
  2011. * @returns the current updated Color4 object
  2012. */
  2013. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2014. this.r = r;
  2015. this.g = g;
  2016. this.b = b;
  2017. this.a = a;
  2018. return this;
  2019. };
  2020. /**
  2021. * Copies the given float values into the current one
  2022. * @param r defines the red component to read from
  2023. * @param g defines the green component to read from
  2024. * @param b defines the blue component to read from
  2025. * @param a defines the alpha component to read from
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.set = function (r, g, b, a) {
  2029. return this.copyFromFloats(r, g, b, a);
  2030. };
  2031. /**
  2032. * Compute the Color4 hexadecimal code as a string
  2033. * @returns a string containing the hexadecimal representation of the Color4 object
  2034. */
  2035. Color4.prototype.toHexString = function () {
  2036. var intR = (this.r * 255) | 0;
  2037. var intG = (this.g * 255) | 0;
  2038. var intB = (this.b * 255) | 0;
  2039. var intA = (this.a * 255) | 0;
  2040. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2041. };
  2042. /**
  2043. * Computes a new Color4 converted from the current one to linear space
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.prototype.toLinearSpace = function () {
  2047. var convertedColor = new Color4();
  2048. this.toLinearSpaceToRef(convertedColor);
  2049. return convertedColor;
  2050. };
  2051. /**
  2052. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2053. * @param convertedColor defines the Color4 object where to store the linear space version
  2054. * @returns the unmodified Color4
  2055. */
  2056. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2057. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2058. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2059. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2060. convertedColor.a = this.a;
  2061. return this;
  2062. };
  2063. /**
  2064. * Computes a new Color4 converted from the current one to gamma space
  2065. * @returns a new Color4 object
  2066. */
  2067. Color4.prototype.toGammaSpace = function () {
  2068. var convertedColor = new Color4();
  2069. this.toGammaSpaceToRef(convertedColor);
  2070. return convertedColor;
  2071. };
  2072. /**
  2073. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2074. * @param convertedColor defines the Color4 object where to store the gamma space version
  2075. * @returns the unmodified Color4
  2076. */
  2077. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2078. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2079. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2080. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2081. convertedColor.a = this.a;
  2082. return this;
  2083. };
  2084. // Statics
  2085. /**
  2086. * Creates a new Color4 from the string containing valid hexadecimal values
  2087. * @param hex defines a string containing valid hexadecimal values
  2088. * @returns a new Color4 object
  2089. */
  2090. Color4.FromHexString = function (hex) {
  2091. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2092. return new Color4(0.0, 0.0, 0.0, 0.0);
  2093. }
  2094. var r = parseInt(hex.substring(1, 3), 16);
  2095. var g = parseInt(hex.substring(3, 5), 16);
  2096. var b = parseInt(hex.substring(5, 7), 16);
  2097. var a = parseInt(hex.substring(7, 9), 16);
  2098. return Color4.FromInts(r, g, b, a);
  2099. };
  2100. /**
  2101. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2102. * @param left defines the start value
  2103. * @param right defines the end value
  2104. * @param amount defines the gradient factor
  2105. * @returns a new Color4 object
  2106. */
  2107. Color4.Lerp = function (left, right, amount) {
  2108. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2109. Color4.LerpToRef(left, right, amount, result);
  2110. return result;
  2111. };
  2112. /**
  2113. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2114. * @param left defines the start value
  2115. * @param right defines the end value
  2116. * @param amount defines the gradient factor
  2117. * @param result defines the Color4 object where to store data
  2118. */
  2119. Color4.LerpToRef = function (left, right, amount, result) {
  2120. result.r = left.r + (right.r - left.r) * amount;
  2121. result.g = left.g + (right.g - left.g) * amount;
  2122. result.b = left.b + (right.b - left.b) * amount;
  2123. result.a = left.a + (right.a - left.a) * amount;
  2124. };
  2125. /**
  2126. * Creates a new Color4 from the starting index element of the given array
  2127. * @param array defines the source array to read from
  2128. * @param offset defines the offset in the source array
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromArray = function (array, offset) {
  2132. if (offset === void 0) { offset = 0; }
  2133. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2134. };
  2135. /**
  2136. * Creates a new Color3 from integer values (< 256)
  2137. * @param r defines the red component to read from (value between 0 and 255)
  2138. * @param g defines the green component to read from (value between 0 and 255)
  2139. * @param b defines the blue component to read from (value between 0 and 255)
  2140. * @param a defines the alpha component to read from (value between 0 and 255)
  2141. * @returns a new Color3 object
  2142. */
  2143. Color4.FromInts = function (r, g, b, a) {
  2144. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2145. };
  2146. /**
  2147. * Check the content of a given array and convert it to an array containing RGBA data
  2148. * If the original array was already containing count * 4 values then it is returned directly
  2149. * @param colors defines the array to check
  2150. * @param count defines the number of RGBA data to expect
  2151. * @returns an array containing count * 4 values (RGBA)
  2152. */
  2153. Color4.CheckColors4 = function (colors, count) {
  2154. // Check if color3 was used
  2155. if (colors.length === count * 3) {
  2156. var colors4 = [];
  2157. for (var index = 0; index < colors.length; index += 3) {
  2158. var newIndex = (index / 3) * 4;
  2159. colors4[newIndex] = colors[index];
  2160. colors4[newIndex + 1] = colors[index + 1];
  2161. colors4[newIndex + 2] = colors[index + 2];
  2162. colors4[newIndex + 3] = 1.0;
  2163. }
  2164. return colors4;
  2165. }
  2166. return colors;
  2167. };
  2168. return Color4;
  2169. }());
  2170. BABYLON.Color4 = Color4;
  2171. /**
  2172. * Class representing a vector containing 2 coordinates
  2173. */
  2174. var Vector2 = /** @class */ (function () {
  2175. /**
  2176. * Creates a new Vector2 from the given x and y coordinates
  2177. * @param x defines the first coordinate
  2178. * @param y defines the second coordinate
  2179. */
  2180. function Vector2(
  2181. /** defines the first coordinate */
  2182. x,
  2183. /** defines the second coordinate */
  2184. y) {
  2185. this.x = x;
  2186. this.y = y;
  2187. }
  2188. /**
  2189. * Gets a string with the Vector2 coordinates
  2190. * @returns a string with the Vector2 coordinates
  2191. */
  2192. Vector2.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + "}";
  2194. };
  2195. /**
  2196. * Gets class name
  2197. * @returns the string "Vector2"
  2198. */
  2199. Vector2.prototype.getClassName = function () {
  2200. return "Vector2";
  2201. };
  2202. /**
  2203. * Gets current vector hash code
  2204. * @returns the Vector2 hash code as a number
  2205. */
  2206. Vector2.prototype.getHashCode = function () {
  2207. var hash = this.x || 0;
  2208. hash = (hash * 397) ^ (this.y || 0);
  2209. return hash;
  2210. };
  2211. // Operators
  2212. /**
  2213. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2214. * @param array defines the source array
  2215. * @param index defines the offset in source array
  2216. * @returns the current Vector2
  2217. */
  2218. Vector2.prototype.toArray = function (array, index) {
  2219. if (index === void 0) { index = 0; }
  2220. array[index] = this.x;
  2221. array[index + 1] = this.y;
  2222. return this;
  2223. };
  2224. /**
  2225. * Copy the current vector to an array
  2226. * @returns a new array with 2 elements: the Vector2 coordinates.
  2227. */
  2228. Vector2.prototype.asArray = function () {
  2229. var result = new Array();
  2230. this.toArray(result, 0);
  2231. return result;
  2232. };
  2233. /**
  2234. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2235. * @param source defines the source Vector2
  2236. * @returns the current updated Vector2
  2237. */
  2238. Vector2.prototype.copyFrom = function (source) {
  2239. this.x = source.x;
  2240. this.y = source.y;
  2241. return this;
  2242. };
  2243. /**
  2244. * Sets the Vector2 coordinates with the given floats
  2245. * @param x defines the first coordinate
  2246. * @param y defines the second coordinate
  2247. * @returns the current updated Vector2
  2248. */
  2249. Vector2.prototype.copyFromFloats = function (x, y) {
  2250. this.x = x;
  2251. this.y = y;
  2252. return this;
  2253. };
  2254. /**
  2255. * Sets the Vector2 coordinates with the given floats
  2256. * @param x defines the first coordinate
  2257. * @param y defines the second coordinate
  2258. * @returns the current updated Vector2
  2259. */
  2260. Vector2.prototype.set = function (x, y) {
  2261. return this.copyFromFloats(x, y);
  2262. };
  2263. /**
  2264. * Add another vector with the current one
  2265. * @param otherVector defines the other vector
  2266. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2267. */
  2268. Vector2.prototype.add = function (otherVector) {
  2269. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2270. };
  2271. /**
  2272. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2273. * @param otherVector defines the other vector
  2274. * @param result defines the target vector
  2275. * @returns the unmodified current Vector2
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2284. * @param otherVector defines the other vector
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.addInPlace = function (otherVector) {
  2288. this.x += otherVector.x;
  2289. this.y += otherVector.y;
  2290. return this;
  2291. };
  2292. /**
  2293. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2294. * @param otherVector defines the other vector
  2295. * @returns a new Vector2
  2296. */
  2297. Vector2.prototype.addVector3 = function (otherVector) {
  2298. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2299. };
  2300. /**
  2301. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2302. * @param otherVector defines the other vector
  2303. * @returns a new Vector2
  2304. */
  2305. Vector2.prototype.subtract = function (otherVector) {
  2306. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2307. };
  2308. /**
  2309. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2310. * @param otherVector defines the other vector
  2311. * @param result defines the target vector
  2312. * @returns the unmodified current Vector2
  2313. */
  2314. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2315. result.x = this.x - otherVector.x;
  2316. result.y = this.y - otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns the current updated Vector2
  2323. */
  2324. Vector2.prototype.subtractInPlace = function (otherVector) {
  2325. this.x -= otherVector.x;
  2326. this.y -= otherVector.y;
  2327. return this;
  2328. };
  2329. /**
  2330. * Multiplies in place the current Vector2 coordinates by the given ones
  2331. * @param otherVector defines the other vector
  2332. * @returns the current updated Vector2
  2333. */
  2334. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2335. this.x *= otherVector.x;
  2336. this.y *= otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2341. * @param otherVector defines the other vector
  2342. * @returns a new Vector2
  2343. */
  2344. Vector2.prototype.multiply = function (otherVector) {
  2345. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2346. };
  2347. /**
  2348. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2349. * @param otherVector defines the other vector
  2350. * @param result defines the target vector
  2351. * @returns the unmodified current Vector2
  2352. */
  2353. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2354. result.x = this.x * otherVector.x;
  2355. result.y = this.y * otherVector.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.multiplyByFloats = function (x, y) {
  2365. return new Vector2(this.x * x, this.y * y);
  2366. };
  2367. /**
  2368. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2369. * @param otherVector defines the other vector
  2370. * @returns a new Vector2
  2371. */
  2372. Vector2.prototype.divide = function (otherVector) {
  2373. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2374. };
  2375. /**
  2376. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2377. * @param otherVector defines the other vector
  2378. * @param result defines the target vector
  2379. * @returns the unmodified current Vector2
  2380. */
  2381. Vector2.prototype.divideToRef = function (otherVector, result) {
  2382. result.x = this.x / otherVector.x;
  2383. result.y = this.y / otherVector.y;
  2384. return this;
  2385. };
  2386. /**
  2387. * Divides the current Vector3 coordinates by the given ones
  2388. * @param otherVector defines the other vector
  2389. * @returns the current updated Vector2
  2390. */
  2391. Vector2.prototype.divideInPlace = function (otherVector) {
  2392. return this.divideToRef(otherVector, this);
  2393. };
  2394. /**
  2395. * Gets a new Vector2 with current Vector2 negated coordinates
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.negate = function () {
  2399. return new Vector2(-this.x, -this.y);
  2400. };
  2401. /**
  2402. * Multiply the Vector2 coordinates by scale
  2403. * @param scale defines the scaling factor
  2404. * @returns the current updated Vector2
  2405. */
  2406. Vector2.prototype.scaleInPlace = function (scale) {
  2407. this.x *= scale;
  2408. this.y *= scale;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2413. * @param scale defines the scaling factor
  2414. * @returns a new Vector2
  2415. */
  2416. Vector2.prototype.scale = function (scale) {
  2417. var result = new Vector2(0, 0);
  2418. this.scaleToRef(scale, result);
  2419. return result;
  2420. };
  2421. /**
  2422. * Scale the current Vector2 values by a factor to a given Vector2
  2423. * @param scale defines the scale factor
  2424. * @param result defines the Vector2 object where to store the result
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.scaleToRef = function (scale, result) {
  2428. result.x = this.x * scale;
  2429. result.y = this.y * scale;
  2430. return this;
  2431. };
  2432. /**
  2433. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2434. * @param scale defines the scale factor
  2435. * @param result defines the Vector2 object where to store the result
  2436. * @returns the unmodified current Vector2
  2437. */
  2438. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2439. result.x += this.x * scale;
  2440. result.y += this.y * scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Gets a boolean if two vectors are equals
  2445. * @param otherVector defines the other vector
  2446. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2447. */
  2448. Vector2.prototype.equals = function (otherVector) {
  2449. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2450. };
  2451. /**
  2452. * Gets a boolean if two vectors are equals (using an epsilon value)
  2453. * @param otherVector defines the other vector
  2454. * @param epsilon defines the minimal distance to consider equality
  2455. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2456. */
  2457. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2458. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2459. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2460. };
  2461. // Properties
  2462. /**
  2463. * Gets the length of the vector
  2464. * @returns the vector length (float)
  2465. */
  2466. Vector2.prototype.length = function () {
  2467. return Math.sqrt(this.x * this.x + this.y * this.y);
  2468. };
  2469. /**
  2470. * Gets the vector squared length
  2471. * @returns the vector squared length (float)
  2472. */
  2473. Vector2.prototype.lengthSquared = function () {
  2474. return (this.x * this.x + this.y * this.y);
  2475. };
  2476. // Methods
  2477. /**
  2478. * Normalize the vector
  2479. * @returns the current updated Vector2
  2480. */
  2481. Vector2.prototype.normalize = function () {
  2482. var len = this.length();
  2483. if (len === 0)
  2484. return this;
  2485. var num = 1.0 / len;
  2486. this.x *= num;
  2487. this.y *= num;
  2488. return this;
  2489. };
  2490. /**
  2491. * Gets a new Vector2 copied from the Vector2
  2492. * @returns a new Vector2
  2493. */
  2494. Vector2.prototype.clone = function () {
  2495. return new Vector2(this.x, this.y);
  2496. };
  2497. // Statics
  2498. /**
  2499. * Gets a new Vector2(0, 0)
  2500. * @returns a new Vector2
  2501. */
  2502. Vector2.Zero = function () {
  2503. return new Vector2(0, 0);
  2504. };
  2505. /**
  2506. * Gets a new Vector2(1, 1)
  2507. * @returns a new Vector2
  2508. */
  2509. Vector2.One = function () {
  2510. return new Vector2(1, 1);
  2511. };
  2512. /**
  2513. * Gets a new Vector2 set from the given index element of the given array
  2514. * @param array defines the data source
  2515. * @param offset defines the offset in the data source
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.FromArray = function (array, offset) {
  2519. if (offset === void 0) { offset = 0; }
  2520. return new Vector2(array[offset], array[offset + 1]);
  2521. };
  2522. /**
  2523. * Sets "result" from the given index element of the given array
  2524. * @param array defines the data source
  2525. * @param offset defines the offset in the data source
  2526. * @param result defines the target vector
  2527. */
  2528. Vector2.FromArrayToRef = function (array, offset, result) {
  2529. result.x = array[offset];
  2530. result.y = array[offset + 1];
  2531. };
  2532. /**
  2533. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2534. * @param value1 defines 1st point of control
  2535. * @param value2 defines 2nd point of control
  2536. * @param value3 defines 3rd point of control
  2537. * @param value4 defines 4th point of control
  2538. * @param amount defines the interpolation factor
  2539. * @returns a new Vector2
  2540. */
  2541. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. return new Vector2(x, y);
  2551. };
  2552. /**
  2553. * 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".
  2554. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2555. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2556. * @param value defines the value to clamp
  2557. * @param min defines the lower limit
  2558. * @param max defines the upper limit
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.Clamp = function (value, min, max) {
  2562. var x = value.x;
  2563. x = (x > max.x) ? max.x : x;
  2564. x = (x < min.x) ? min.x : x;
  2565. var y = value.y;
  2566. y = (y > max.y) ? max.y : y;
  2567. y = (y < min.y) ? min.y : y;
  2568. return new Vector2(x, y);
  2569. };
  2570. /**
  2571. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2572. * @param value1 defines the 1st control point
  2573. * @param tangent1 defines the outgoing tangent
  2574. * @param value2 defines the 2nd control point
  2575. * @param tangent2 defines the incoming tangent
  2576. * @param amount defines the interpolation factor
  2577. * @returns a new Vector2
  2578. */
  2579. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2580. var squared = amount * amount;
  2581. var cubed = amount * squared;
  2582. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2583. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2584. var part3 = (cubed - (2.0 * squared)) + amount;
  2585. var part4 = cubed - squared;
  2586. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2587. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2588. return new Vector2(x, y);
  2589. };
  2590. /**
  2591. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2592. * @param start defines the start vector
  2593. * @param end defines the end vector
  2594. * @param amount defines the interpolation factor
  2595. * @returns a new Vector2
  2596. */
  2597. Vector2.Lerp = function (start, end, amount) {
  2598. var x = start.x + ((end.x - start.x) * amount);
  2599. var y = start.y + ((end.y - start.y) * amount);
  2600. return new Vector2(x, y);
  2601. };
  2602. /**
  2603. * Gets the dot product of the vector "left" and the vector "right"
  2604. * @param left defines first vector
  2605. * @param right defines second vector
  2606. * @returns the dot product (float)
  2607. */
  2608. Vector2.Dot = function (left, right) {
  2609. return left.x * right.x + left.y * right.y;
  2610. };
  2611. /**
  2612. * Returns a new Vector2 equal to the normalized given vector
  2613. * @param vector defines the vector to normalize
  2614. * @returns a new Vector2
  2615. */
  2616. Vector2.Normalize = function (vector) {
  2617. var newVector = vector.clone();
  2618. newVector.normalize();
  2619. return newVector;
  2620. };
  2621. /**
  2622. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2623. * @param left defines 1st vector
  2624. * @param right defines 2nd vector
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.Minimize = function (left, right) {
  2628. var x = (left.x < right.x) ? left.x : right.x;
  2629. var y = (left.y < right.y) ? left.y : right.y;
  2630. return new Vector2(x, y);
  2631. };
  2632. /**
  2633. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2634. * @param left defines 1st vector
  2635. * @param right defines 2nd vector
  2636. * @returns a new Vector2
  2637. */
  2638. Vector2.Maximize = function (left, right) {
  2639. var x = (left.x > right.x) ? left.x : right.x;
  2640. var y = (left.y > right.y) ? left.y : right.y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2645. * @param vector defines the vector to transform
  2646. * @param transformation defines the matrix to apply
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Transform = function (vector, transformation) {
  2650. var r = Vector2.Zero();
  2651. Vector2.TransformToRef(vector, transformation, r);
  2652. return r;
  2653. };
  2654. /**
  2655. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2656. * @param vector defines the vector to transform
  2657. * @param transformation defines the matrix to apply
  2658. * @param result defines the target vector
  2659. */
  2660. Vector2.TransformToRef = function (vector, transformation, result) {
  2661. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2662. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2663. result.x = x;
  2664. result.y = y;
  2665. };
  2666. /**
  2667. * Determines if a given vector is included in a triangle
  2668. * @param p defines the vector to test
  2669. * @param p0 defines 1st triangle point
  2670. * @param p1 defines 2nd triangle point
  2671. * @param p2 defines 3rd triangle point
  2672. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2673. */
  2674. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2675. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2676. var sign = a < 0 ? -1 : 1;
  2677. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2678. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2679. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2680. };
  2681. /**
  2682. * Gets the distance between the vectors "value1" and "value2"
  2683. * @param value1 defines first vector
  2684. * @param value2 defines second vector
  2685. * @returns the distance between vectors
  2686. */
  2687. Vector2.Distance = function (value1, value2) {
  2688. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2689. };
  2690. /**
  2691. * Returns the squared distance between the vectors "value1" and "value2"
  2692. * @param value1 defines first vector
  2693. * @param value2 defines second vector
  2694. * @returns the squared distance between vectors
  2695. */
  2696. Vector2.DistanceSquared = function (value1, value2) {
  2697. var x = value1.x - value2.x;
  2698. var y = value1.y - value2.y;
  2699. return (x * x) + (y * y);
  2700. };
  2701. /**
  2702. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2703. * @param value1 defines first vector
  2704. * @param value2 defines second vector
  2705. * @returns a new Vector2
  2706. */
  2707. Vector2.Center = function (value1, value2) {
  2708. var center = value1.add(value2);
  2709. center.scaleInPlace(0.5);
  2710. return center;
  2711. };
  2712. /**
  2713. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2714. * @param p defines the middle point
  2715. * @param segA defines one point of the segment
  2716. * @param segB defines the other point of the segment
  2717. * @returns the shortest distance
  2718. */
  2719. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2720. var l2 = Vector2.DistanceSquared(segA, segB);
  2721. if (l2 === 0.0) {
  2722. return Vector2.Distance(p, segA);
  2723. }
  2724. var v = segB.subtract(segA);
  2725. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2726. var proj = segA.add(v.multiplyByFloats(t, t));
  2727. return Vector2.Distance(p, proj);
  2728. };
  2729. return Vector2;
  2730. }());
  2731. BABYLON.Vector2 = Vector2;
  2732. /**
  2733. * Classed used to store (x,y,z) vector representation
  2734. * A Vector3 is the main object used in 3D geometry
  2735. * It can represent etiher the coordinates of a point the space, either a direction
  2736. * Reminder: Babylon.js uses a left handed forward facing system
  2737. */
  2738. var Vector3 = /** @class */ (function () {
  2739. /**
  2740. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2741. * @param x defines the first coordinates (on X axis)
  2742. * @param y defines the second coordinates (on Y axis)
  2743. * @param z defines the third coordinates (on Z axis)
  2744. */
  2745. function Vector3(
  2746. /**
  2747. * Defines the first coordinates (on X axis)
  2748. */
  2749. x,
  2750. /**
  2751. * Defines the second coordinates (on Y axis)
  2752. */
  2753. y,
  2754. /**
  2755. * Defines the third coordinates (on Z axis)
  2756. */
  2757. z) {
  2758. this.x = x;
  2759. this.y = y;
  2760. this.z = z;
  2761. }
  2762. /**
  2763. * Creates a string representation of the Vector3
  2764. * @returns a string with the Vector3 coordinates.
  2765. */
  2766. Vector3.prototype.toString = function () {
  2767. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2768. };
  2769. /**
  2770. * Gets the class name
  2771. * @returns the string "Vector3"
  2772. */
  2773. Vector3.prototype.getClassName = function () {
  2774. return "Vector3";
  2775. };
  2776. /**
  2777. * Creates the Vector3 hash code
  2778. * @returns a number which tends to be unique between Vector3 instances
  2779. */
  2780. Vector3.prototype.getHashCode = function () {
  2781. var hash = this.x || 0;
  2782. hash = (hash * 397) ^ (this.y || 0);
  2783. hash = (hash * 397) ^ (this.z || 0);
  2784. return hash;
  2785. };
  2786. // Operators
  2787. /**
  2788. * Creates an array containing three elements : the coordinates of the Vector3
  2789. * @returns a new array of numbers
  2790. */
  2791. Vector3.prototype.asArray = function () {
  2792. var result = [];
  2793. this.toArray(result, 0);
  2794. return result;
  2795. };
  2796. /**
  2797. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2798. * @param array defines the destination array
  2799. * @param index defines the offset in the destination array
  2800. * @returns the current Vector3
  2801. */
  2802. Vector3.prototype.toArray = function (array, index) {
  2803. if (index === void 0) { index = 0; }
  2804. array[index] = this.x;
  2805. array[index + 1] = this.y;
  2806. array[index + 2] = this.z;
  2807. return this;
  2808. };
  2809. /**
  2810. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2811. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2812. */
  2813. Vector3.prototype.toQuaternion = function () {
  2814. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2815. };
  2816. /**
  2817. * Adds the given vector to the current Vector3
  2818. * @param otherVector defines the second operand
  2819. * @returns the current updated Vector3
  2820. */
  2821. Vector3.prototype.addInPlace = function (otherVector) {
  2822. this.x += otherVector.x;
  2823. this.y += otherVector.y;
  2824. this.z += otherVector.z;
  2825. return this;
  2826. };
  2827. /**
  2828. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2829. * @param otherVector defines the second operand
  2830. * @returns the resulting Vector3
  2831. */
  2832. Vector3.prototype.add = function (otherVector) {
  2833. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2834. };
  2835. /**
  2836. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2837. * @param otherVector defines the second operand
  2838. * @param result defines the Vector3 object where to store the result
  2839. * @returns the current Vector3
  2840. */
  2841. Vector3.prototype.addToRef = function (otherVector, result) {
  2842. result.x = this.x + otherVector.x;
  2843. result.y = this.y + otherVector.y;
  2844. result.z = this.z + otherVector.z;
  2845. return this;
  2846. };
  2847. /**
  2848. * Subtract the given vector from the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.subtractInPlace = function (otherVector) {
  2853. this.x -= otherVector.x;
  2854. this.y -= otherVector.y;
  2855. this.z -= otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.subtract = function (otherVector) {
  2864. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2865. };
  2866. /**
  2867. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2873. result.x = this.x - otherVector.x;
  2874. result.y = this.y - otherVector.y;
  2875. result.z = this.z - otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2880. * @param x defines the x coordinate of the operand
  2881. * @param y defines the y coordinate of the operand
  2882. * @param z defines the z coordinate of the operand
  2883. * @returns the resulting Vector3
  2884. */
  2885. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2886. return new Vector3(this.x - x, this.y - y, this.z - z);
  2887. };
  2888. /**
  2889. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2890. * @param x defines the x coordinate of the operand
  2891. * @param y defines the y coordinate of the operand
  2892. * @param z defines the z coordinate of the operand
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2897. result.x = this.x - x;
  2898. result.y = this.y - y;
  2899. result.z = this.z - z;
  2900. return this;
  2901. };
  2902. /**
  2903. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2904. * @returns a new Vector3
  2905. */
  2906. Vector3.prototype.negate = function () {
  2907. return new Vector3(-this.x, -this.y, -this.z);
  2908. };
  2909. /**
  2910. * Multiplies the Vector3 coordinates by the float "scale"
  2911. * @param scale defines the multiplier factor
  2912. * @returns the current updated Vector3
  2913. */
  2914. Vector3.prototype.scaleInPlace = function (scale) {
  2915. this.x *= scale;
  2916. this.y *= scale;
  2917. this.z *= scale;
  2918. return this;
  2919. };
  2920. /**
  2921. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2922. * @param scale defines the multiplier factor
  2923. * @returns a new Vector3
  2924. */
  2925. Vector3.prototype.scale = function (scale) {
  2926. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2927. };
  2928. /**
  2929. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2930. * @param scale defines the multiplier factor
  2931. * @param result defines the Vector3 object where to store the result
  2932. * @returns the current Vector3
  2933. */
  2934. Vector3.prototype.scaleToRef = function (scale, result) {
  2935. result.x = this.x * scale;
  2936. result.y = this.y * scale;
  2937. result.z = this.z * scale;
  2938. return this;
  2939. };
  2940. /**
  2941. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2942. * @param scale defines the scale factor
  2943. * @param result defines the Vector3 object where to store the result
  2944. * @returns the unmodified current Vector3
  2945. */
  2946. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2947. result.x += this.x * scale;
  2948. result.y += this.y * scale;
  2949. result.z += this.z * scale;
  2950. return this;
  2951. };
  2952. /**
  2953. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2954. * @param otherVector defines the second operand
  2955. * @returns true if both vectors are equals
  2956. */
  2957. Vector3.prototype.equals = function (otherVector) {
  2958. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2959. };
  2960. /**
  2961. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2962. * @param otherVector defines the second operand
  2963. * @param epsilon defines the minimal distance to define values as equals
  2964. * @returns true if both vectors are distant less than epsilon
  2965. */
  2966. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2967. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2968. 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);
  2969. };
  2970. /**
  2971. * Returns true if the current Vector3 coordinates equals the given floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns true if both vectors are equals
  2976. */
  2977. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2978. return this.x === x && this.y === y && this.z === z;
  2979. };
  2980. /**
  2981. * Multiplies the current Vector3 coordinates by the given ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the current updated Vector3
  2984. */
  2985. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2986. this.x *= otherVector.x;
  2987. this.y *= otherVector.y;
  2988. this.z *= otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2993. * @param otherVector defines the second operand
  2994. * @returns the new Vector3
  2995. */
  2996. Vector3.prototype.multiply = function (otherVector) {
  2997. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2998. };
  2999. /**
  3000. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3001. * @param otherVector defines the second operand
  3002. * @param result defines the Vector3 object where to store the result
  3003. * @returns the current Vector3
  3004. */
  3005. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3006. result.x = this.x * otherVector.x;
  3007. result.y = this.y * otherVector.y;
  3008. result.z = this.z * otherVector.z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3013. * @param x defines the x coordinate of the operand
  3014. * @param y defines the y coordinate of the operand
  3015. * @param z defines the z coordinate of the operand
  3016. * @returns the new Vector3
  3017. */
  3018. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3019. return new Vector3(this.x * x, this.y * y, this.z * z);
  3020. };
  3021. /**
  3022. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3023. * @param otherVector defines the second operand
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.divide = function (otherVector) {
  3027. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3028. };
  3029. /**
  3030. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3031. * @param otherVector defines the second operand
  3032. * @param result defines the Vector3 object where to store the result
  3033. * @returns the current Vector3
  3034. */
  3035. Vector3.prototype.divideToRef = function (otherVector, result) {
  3036. result.x = this.x / otherVector.x;
  3037. result.y = this.y / otherVector.y;
  3038. result.z = this.z / otherVector.z;
  3039. return this;
  3040. };
  3041. /**
  3042. * Divides the current Vector3 coordinates by the given ones.
  3043. * @param otherVector defines the second operand
  3044. * @returns the current updated Vector3
  3045. */
  3046. Vector3.prototype.divideInPlace = function (otherVector) {
  3047. return this.divideToRef(otherVector, this);
  3048. };
  3049. /**
  3050. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3051. * @param other defines the second operand
  3052. * @returns the current updated Vector3
  3053. */
  3054. Vector3.prototype.minimizeInPlace = function (other) {
  3055. if (other.x < this.x)
  3056. this.x = other.x;
  3057. if (other.y < this.y)
  3058. this.y = other.y;
  3059. if (other.z < this.z)
  3060. this.z = other.z;
  3061. return this;
  3062. };
  3063. /**
  3064. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3065. * @param other defines the second operand
  3066. * @returns the current updated Vector3
  3067. */
  3068. Vector3.prototype.maximizeInPlace = function (other) {
  3069. if (other.x > this.x)
  3070. this.x = other.x;
  3071. if (other.y > this.y)
  3072. this.y = other.y;
  3073. if (other.z > this.z)
  3074. this.z = other.z;
  3075. return this;
  3076. };
  3077. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3078. /**
  3079. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3080. */
  3081. get: function () {
  3082. var absX = Math.abs(this.x);
  3083. var absY = Math.abs(this.y);
  3084. if (absX !== absY) {
  3085. return true;
  3086. }
  3087. var absZ = Math.abs(this.z);
  3088. if (absX !== absZ) {
  3089. return true;
  3090. }
  3091. if (absY !== absZ) {
  3092. return true;
  3093. }
  3094. return false;
  3095. },
  3096. enumerable: true,
  3097. configurable: true
  3098. });
  3099. // Properties
  3100. /**
  3101. * Gets the length of the Vector3
  3102. * @returns the length of the Vecto3
  3103. */
  3104. Vector3.prototype.length = function () {
  3105. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3106. };
  3107. /**
  3108. * Gets the squared length of the Vector3
  3109. * @returns squared length of the Vector3
  3110. */
  3111. Vector3.prototype.lengthSquared = function () {
  3112. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3113. };
  3114. /**
  3115. * Normalize the current Vector3.
  3116. * Please note that this is an in place operation.
  3117. * @returns the current updated Vector3
  3118. */
  3119. Vector3.prototype.normalize = function () {
  3120. var len = this.length();
  3121. if (len === 0 || len === 1.0)
  3122. return this;
  3123. var num = 1.0 / len;
  3124. this.x *= num;
  3125. this.y *= num;
  3126. this.z *= num;
  3127. return this;
  3128. };
  3129. /**
  3130. * Normalize the current Vector3 to a new vector
  3131. * @returns the new Vector3
  3132. */
  3133. Vector3.prototype.normalizeToNew = function () {
  3134. var normalized = new Vector3(0, 0, 0);
  3135. this.normalizeToRef(normalized);
  3136. return normalized;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to the reference
  3140. * @param reference define the Vector3 to update
  3141. * @returns the updated Vector3
  3142. */
  3143. Vector3.prototype.normalizeToRef = function (reference) {
  3144. var len = this.length();
  3145. if (len === 0 || len === 1.0) {
  3146. reference.set(this.x, this.y, this.z);
  3147. return reference;
  3148. }
  3149. var scale = 1.0 / len;
  3150. this.scaleToRef(scale, reference);
  3151. return reference;
  3152. };
  3153. /**
  3154. * Creates a new Vector3 copied from the current Vector3
  3155. * @returns the new Vector3
  3156. */
  3157. Vector3.prototype.clone = function () {
  3158. return new Vector3(this.x, this.y, this.z);
  3159. };
  3160. /**
  3161. * Copies the given vector coordinates to the current Vector3 ones
  3162. * @param source defines the source Vector3
  3163. * @returns the current updated Vector3
  3164. */
  3165. Vector3.prototype.copyFrom = function (source) {
  3166. this.x = source.x;
  3167. this.y = source.y;
  3168. this.z = source.z;
  3169. return this;
  3170. };
  3171. /**
  3172. * Copies the given floats to the current Vector3 coordinates
  3173. * @param x defines the x coordinate of the operand
  3174. * @param y defines the y coordinate of the operand
  3175. * @param z defines the z coordinate of the operand
  3176. * @returns the current updated Vector3
  3177. */
  3178. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3179. this.x = x;
  3180. this.y = y;
  3181. this.z = z;
  3182. return this;
  3183. };
  3184. /**
  3185. * Copies the given floats to the current Vector3 coordinates
  3186. * @param x defines the x coordinate of the operand
  3187. * @param y defines the y coordinate of the operand
  3188. * @param z defines the z coordinate of the operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.set = function (x, y, z) {
  3192. return this.copyFromFloats(x, y, z);
  3193. };
  3194. // Statics
  3195. /**
  3196. * Get the clip factor between two vectors
  3197. * @param vector0 defines the first operand
  3198. * @param vector1 defines the second operand
  3199. * @param axis defines the axis to use
  3200. * @param size defines the size along the axis
  3201. * @returns the clip factor
  3202. */
  3203. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3204. var d0 = Vector3.Dot(vector0, axis) - size;
  3205. var d1 = Vector3.Dot(vector1, axis) - size;
  3206. var s = d0 / (d0 - d1);
  3207. return s;
  3208. };
  3209. /**
  3210. * Get angle between two vectors
  3211. * @param vector0 angle between vector0 and vector1
  3212. * @param vector1 angle between vector0 and vector1
  3213. * @param normal direction of the normal
  3214. * @return the angle between vector0 and vector1
  3215. */
  3216. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3217. var v0 = vector0.clone().normalize();
  3218. var v1 = vector1.clone().normalize();
  3219. var dot = Vector3.Dot(v0, v1);
  3220. var n = Vector3.Cross(v0, v1);
  3221. if (Vector3.Dot(n, normal) > 0) {
  3222. return Math.acos(dot);
  3223. }
  3224. return -Math.acos(dot);
  3225. };
  3226. /**
  3227. * Returns a new Vector3 set from the index "offset" of the given array
  3228. * @param array defines the source array
  3229. * @param offset defines the offset in the source array
  3230. * @returns the new Vector3
  3231. */
  3232. Vector3.FromArray = function (array, offset) {
  3233. if (!offset) {
  3234. offset = 0;
  3235. }
  3236. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3237. };
  3238. /**
  3239. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3240. * This function is deprecated. Use FromArray instead
  3241. * @param array defines the source array
  3242. * @param offset defines the offset in the source array
  3243. * @returns the new Vector3
  3244. */
  3245. Vector3.FromFloatArray = function (array, offset) {
  3246. return Vector3.FromArray(array, offset);
  3247. };
  3248. /**
  3249. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @param result defines the Vector3 where to store the result
  3253. */
  3254. Vector3.FromArrayToRef = function (array, offset, result) {
  3255. result.x = array[offset];
  3256. result.y = array[offset + 1];
  3257. result.z = array[offset + 2];
  3258. };
  3259. /**
  3260. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3261. * This function is deprecated. Use FromArrayToRef instead.
  3262. * @param array defines the source array
  3263. * @param offset defines the offset in the source array
  3264. * @param result defines the Vector3 where to store the result
  3265. */
  3266. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3267. return Vector3.FromArrayToRef(array, offset, result);
  3268. };
  3269. /**
  3270. * Sets the given vector "result" with the given floats.
  3271. * @param x defines the x coordinate of the source
  3272. * @param y defines the y coordinate of the source
  3273. * @param z defines the z coordinate of the source
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3277. result.x = x;
  3278. result.y = y;
  3279. result.z = z;
  3280. };
  3281. /**
  3282. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3283. * @returns a new empty Vector3
  3284. */
  3285. Vector3.Zero = function () {
  3286. return new Vector3(0.0, 0.0, 0.0);
  3287. };
  3288. /**
  3289. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3290. * @returns a new unit Vector3
  3291. */
  3292. Vector3.One = function () {
  3293. return new Vector3(1.0, 1.0, 1.0);
  3294. };
  3295. /**
  3296. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3297. * @returns a new up Vector3
  3298. */
  3299. Vector3.Up = function () {
  3300. return new Vector3(0.0, 1.0, 0.0);
  3301. };
  3302. /**
  3303. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3304. * @returns a new forward Vector3
  3305. */
  3306. Vector3.Forward = function () {
  3307. return new Vector3(0.0, 0.0, 1.0);
  3308. };
  3309. /**
  3310. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3311. * @returns a new right Vector3
  3312. */
  3313. Vector3.Right = function () {
  3314. return new Vector3(1.0, 0.0, 0.0);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3318. * @returns a new left Vector3
  3319. */
  3320. Vector3.Left = function () {
  3321. return new Vector3(-1.0, 0.0, 0.0);
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3325. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3326. * @param vector defines the Vector3 to transform
  3327. * @param transformation defines the transformation matrix
  3328. * @returns the transformed Vector3
  3329. */
  3330. Vector3.TransformCoordinates = function (vector, transformation) {
  3331. var result = Vector3.Zero();
  3332. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3337. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3338. * @param vector defines the Vector3 to transform
  3339. * @param transformation defines the transformation matrix
  3340. * @param result defines the Vector3 where to store the result
  3341. */
  3342. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3343. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3344. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3345. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3346. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3347. result.x = x / w;
  3348. result.y = y / w;
  3349. result.z = z / w;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3353. * This method computes tranformed coordinates only, not transformed direction vectors
  3354. * @param x define the x coordinate of the source vector
  3355. * @param y define the y coordinate of the source vector
  3356. * @param z define the z coordinate of the source vector
  3357. * @param transformation defines the transformation matrix
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3361. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3362. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3363. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3364. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3365. result.x = rx / rw;
  3366. result.y = ry / rw;
  3367. result.z = rz / rw;
  3368. };
  3369. /**
  3370. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3371. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3372. * @param vector defines the Vector3 to transform
  3373. * @param transformation defines the transformation matrix
  3374. * @returns the new Vector3
  3375. */
  3376. Vector3.TransformNormal = function (vector, transformation) {
  3377. var result = Vector3.Zero();
  3378. Vector3.TransformNormalToRef(vector, transformation, result);
  3379. return result;
  3380. };
  3381. /**
  3382. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3383. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3384. * @param vector defines the Vector3 to transform
  3385. * @param transformation defines the transformation matrix
  3386. * @param result defines the Vector3 where to store the result
  3387. */
  3388. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3389. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3390. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3391. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3392. result.x = x;
  3393. result.y = y;
  3394. result.z = z;
  3395. };
  3396. /**
  3397. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param x define the x coordinate of the source vector
  3400. * @param y define the y coordinate of the source vector
  3401. * @param z define the z coordinate of the source vector
  3402. * @param transformation defines the transformation matrix
  3403. * @param result defines the Vector3 where to store the result
  3404. */
  3405. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3406. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3407. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3408. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3409. };
  3410. /**
  3411. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3412. * @param value1 defines the first control point
  3413. * @param value2 defines the second control point
  3414. * @param value3 defines the third control point
  3415. * @param value4 defines the fourth control point
  3416. * @param amount defines the amount on the spline to use
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3420. var squared = amount * amount;
  3421. var cubed = amount * squared;
  3422. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3423. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3424. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3425. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3426. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3427. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3428. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3429. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3430. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3431. return new Vector3(x, y, z);
  3432. };
  3433. /**
  3434. * 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"
  3435. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3436. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3437. * @param value defines the current value
  3438. * @param min defines the lower range value
  3439. * @param max defines the upper range value
  3440. * @returns the new Vector3
  3441. */
  3442. Vector3.Clamp = function (value, min, max) {
  3443. var x = value.x;
  3444. x = (x > max.x) ? max.x : x;
  3445. x = (x < min.x) ? min.x : x;
  3446. var y = value.y;
  3447. y = (y > max.y) ? max.y : y;
  3448. y = (y < min.y) ? min.y : y;
  3449. var z = value.z;
  3450. z = (z > max.z) ? max.z : z;
  3451. z = (z < min.z) ? min.z : z;
  3452. return new Vector3(x, y, z);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3456. * @param value1 defines the first control point
  3457. * @param tangent1 defines the first tangent vector
  3458. * @param value2 defines the second control point
  3459. * @param tangent2 defines the second tangent vector
  3460. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3461. * @returns the new Vector3
  3462. */
  3463. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3464. var squared = amount * amount;
  3465. var cubed = amount * squared;
  3466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3468. var part3 = (cubed - (2.0 * squared)) + amount;
  3469. var part4 = cubed - squared;
  3470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3472. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3473. return new Vector3(x, y, z);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3477. * @param start defines the start value
  3478. * @param end defines the end value
  3479. * @param amount max defines amount between both (between 0 and 1)
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.Lerp = function (start, end, amount) {
  3483. var result = new Vector3(0, 0, 0);
  3484. Vector3.LerpToRef(start, end, amount, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3489. * @param start defines the start value
  3490. * @param end defines the end value
  3491. * @param amount max defines amount between both (between 0 and 1)
  3492. * @param result defines the Vector3 where to store the result
  3493. */
  3494. Vector3.LerpToRef = function (start, end, amount, result) {
  3495. result.x = start.x + ((end.x - start.x) * amount);
  3496. result.y = start.y + ((end.y - start.y) * amount);
  3497. result.z = start.z + ((end.z - start.z) * amount);
  3498. };
  3499. /**
  3500. * Returns the dot product (float) between the vectors "left" and "right"
  3501. * @param left defines the left operand
  3502. * @param right defines the right operand
  3503. * @returns the dot product
  3504. */
  3505. Vector3.Dot = function (left, right) {
  3506. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3507. };
  3508. /**
  3509. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3510. * The cross product is then orthogonal to both "left" and "right"
  3511. * @param left defines the left operand
  3512. * @param right defines the right operand
  3513. * @returns the cross product
  3514. */
  3515. Vector3.Cross = function (left, right) {
  3516. var result = Vector3.Zero();
  3517. Vector3.CrossToRef(left, right, result);
  3518. return result;
  3519. };
  3520. /**
  3521. * Sets the given vector "result" with the cross product of "left" and "right"
  3522. * The cross product is then orthogonal to both "left" and "right"
  3523. * @param left defines the left operand
  3524. * @param right defines the right operand
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.CrossToRef = function (left, right, result) {
  3528. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3529. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3530. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3531. result.copyFrom(MathTmp.Vector3[0]);
  3532. };
  3533. /**
  3534. * Returns a new Vector3 as the normalization of the given vector
  3535. * @param vector defines the Vector3 to normalize
  3536. * @returns the new Vector3
  3537. */
  3538. Vector3.Normalize = function (vector) {
  3539. var result = Vector3.Zero();
  3540. Vector3.NormalizeToRef(vector, result);
  3541. return result;
  3542. };
  3543. /**
  3544. * Sets the given vector "result" with the normalization of the given first vector
  3545. * @param vector defines the Vector3 to normalize
  3546. * @param result defines the Vector3 where to store the result
  3547. */
  3548. Vector3.NormalizeToRef = function (vector, result) {
  3549. result.copyFrom(vector);
  3550. result.normalize();
  3551. };
  3552. /**
  3553. * Project a Vector3 onto screen space
  3554. * @param vector defines the Vector3 to project
  3555. * @param world defines the world matrix to use
  3556. * @param transform defines the transform (view x projection) matrix to use
  3557. * @param viewport defines the screen viewport to use
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Project = function (vector, world, transform, viewport) {
  3561. var cw = viewport.width;
  3562. var ch = viewport.height;
  3563. var cx = viewport.x;
  3564. var cy = viewport.y;
  3565. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3566. 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);
  3567. var matrix = MathTmp.Matrix[0];
  3568. world.multiplyToRef(transform, matrix);
  3569. matrix.multiplyToRef(viewportMatrix, matrix);
  3570. return Vector3.TransformCoordinates(vector, matrix);
  3571. };
  3572. /**
  3573. * Unproject from screen space to object space
  3574. * @param source defines the screen space Vector3 to use
  3575. * @param viewportWidth defines the current width of the viewport
  3576. * @param viewportHeight defines the current height of the viewport
  3577. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3578. * @param transform defines the transform (view x projection) matrix to use
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3582. var matrix = MathTmp.Matrix[0];
  3583. world.multiplyToRef(transform, matrix);
  3584. matrix.invert();
  3585. source.x = source.x / viewportWidth * 2 - 1;
  3586. source.y = -(source.y / viewportHeight * 2 - 1);
  3587. var vector = Vector3.TransformCoordinates(source, matrix);
  3588. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3589. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3590. vector = vector.scale(1.0 / num);
  3591. }
  3592. return vector;
  3593. };
  3594. /**
  3595. * Unproject from screen space to object space
  3596. * @param source defines the screen space Vector3 to use
  3597. * @param viewportWidth defines the current width of the viewport
  3598. * @param viewportHeight defines the current height of the viewport
  3599. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3600. * @param view defines the view matrix to use
  3601. * @param projection defines the projection matrix to use
  3602. * @returns the new Vector3
  3603. */
  3604. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3605. var result = Vector3.Zero();
  3606. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3607. return result;
  3608. };
  3609. /**
  3610. * Unproject from screen space to object space
  3611. * @param source defines the screen space Vector3 to use
  3612. * @param viewportWidth defines the current width of the viewport
  3613. * @param viewportHeight defines the current height of the viewport
  3614. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3615. * @param view defines the view matrix to use
  3616. * @param projection defines the projection matrix to use
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3620. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3621. };
  3622. /**
  3623. * Unproject from screen space to object space
  3624. * @param sourceX defines the screen space x coordinate to use
  3625. * @param sourceY defines the screen space y coordinate to use
  3626. * @param sourceZ defines the screen space z coordinate to use
  3627. * @param viewportWidth defines the current width of the viewport
  3628. * @param viewportHeight defines the current height of the viewport
  3629. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3630. * @param view defines the view matrix to use
  3631. * @param projection defines the projection matrix to use
  3632. * @param result defines the Vector3 where to store the result
  3633. */
  3634. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3635. var matrix = MathTmp.Matrix[0];
  3636. world.multiplyToRef(view, matrix);
  3637. matrix.multiplyToRef(projection, matrix);
  3638. matrix.invert();
  3639. var screenSource = MathTmp.Vector3[0];
  3640. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3641. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3642. screenSource.z = 2 * sourceZ - 1.0;
  3643. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3644. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3645. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3646. result.scaleInPlace(1.0 / num);
  3647. }
  3648. };
  3649. /**
  3650. * Gets the minimal coordinate values between two Vector3
  3651. * @param left defines the first operand
  3652. * @param right defines the second operand
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Minimize = function (left, right) {
  3656. var min = left.clone();
  3657. min.minimizeInPlace(right);
  3658. return min;
  3659. };
  3660. /**
  3661. * Gets the maximal coordinate values between two Vector3
  3662. * @param left defines the first operand
  3663. * @param right defines the second operand
  3664. * @returns the new Vector3
  3665. */
  3666. Vector3.Maximize = function (left, right) {
  3667. var max = left.clone();
  3668. max.maximizeInPlace(right);
  3669. return max;
  3670. };
  3671. /**
  3672. * Returns the distance between the vectors "value1" and "value2"
  3673. * @param value1 defines the first operand
  3674. * @param value2 defines the second operand
  3675. * @returns the distance
  3676. */
  3677. Vector3.Distance = function (value1, value2) {
  3678. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3679. };
  3680. /**
  3681. * Returns the squared distance between the vectors "value1" and "value2"
  3682. * @param value1 defines the first operand
  3683. * @param value2 defines the second operand
  3684. * @returns the squared distance
  3685. */
  3686. Vector3.DistanceSquared = function (value1, value2) {
  3687. var x = value1.x - value2.x;
  3688. var y = value1.y - value2.y;
  3689. var z = value1.z - value2.z;
  3690. return (x * x) + (y * y) + (z * z);
  3691. };
  3692. /**
  3693. * Returns a new Vector3 located at the center between "value1" and "value2"
  3694. * @param value1 defines the first operand
  3695. * @param value2 defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Center = function (value1, value2) {
  3699. var center = value1.add(value2);
  3700. center.scaleInPlace(0.5);
  3701. return center;
  3702. };
  3703. /**
  3704. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3705. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3706. * to something in order to rotate it from its local system to the given target system
  3707. * Note: axis1, axis2 and axis3 are normalized during this operation
  3708. * @param axis1 defines the first axis
  3709. * @param axis2 defines the second axis
  3710. * @param axis3 defines the third axis
  3711. * @returns a new Vector3
  3712. */
  3713. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3714. var rotation = Vector3.Zero();
  3715. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3716. return rotation;
  3717. };
  3718. /**
  3719. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3720. * @param axis1 defines the first axis
  3721. * @param axis2 defines the second axis
  3722. * @param axis3 defines the third axis
  3723. * @param ref defines the Vector3 where to store the result
  3724. */
  3725. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3726. var quat = MathTmp.Quaternion[0];
  3727. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3728. quat.toEulerAnglesToRef(ref);
  3729. };
  3730. return Vector3;
  3731. }());
  3732. BABYLON.Vector3 = Vector3;
  3733. //Vector4 class created for EulerAngle class conversion to Quaternion
  3734. var Vector4 = /** @class */ (function () {
  3735. /**
  3736. * Creates a Vector4 object from the given floats.
  3737. */
  3738. function Vector4(x, y, z, w) {
  3739. this.x = x;
  3740. this.y = y;
  3741. this.z = z;
  3742. this.w = w;
  3743. }
  3744. /**
  3745. * Returns the string with the Vector4 coordinates.
  3746. */
  3747. Vector4.prototype.toString = function () {
  3748. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3749. };
  3750. /**
  3751. * Returns the string "Vector4".
  3752. */
  3753. Vector4.prototype.getClassName = function () {
  3754. return "Vector4";
  3755. };
  3756. /**
  3757. * Returns the Vector4 hash code.
  3758. */
  3759. Vector4.prototype.getHashCode = function () {
  3760. var hash = this.x || 0;
  3761. hash = (hash * 397) ^ (this.y || 0);
  3762. hash = (hash * 397) ^ (this.z || 0);
  3763. hash = (hash * 397) ^ (this.w || 0);
  3764. return hash;
  3765. };
  3766. // Operators
  3767. /**
  3768. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3769. */
  3770. Vector4.prototype.asArray = function () {
  3771. var result = new Array();
  3772. this.toArray(result, 0);
  3773. return result;
  3774. };
  3775. /**
  3776. * Populates the given array from the given index with the Vector4 coordinates.
  3777. * Returns the Vector4.
  3778. */
  3779. Vector4.prototype.toArray = function (array, index) {
  3780. if (index === undefined) {
  3781. index = 0;
  3782. }
  3783. array[index] = this.x;
  3784. array[index + 1] = this.y;
  3785. array[index + 2] = this.z;
  3786. array[index + 3] = this.w;
  3787. return this;
  3788. };
  3789. /**
  3790. * Adds the given vector to the current Vector4.
  3791. * Returns the updated Vector4.
  3792. */
  3793. Vector4.prototype.addInPlace = function (otherVector) {
  3794. this.x += otherVector.x;
  3795. this.y += otherVector.y;
  3796. this.z += otherVector.z;
  3797. this.w += otherVector.w;
  3798. return this;
  3799. };
  3800. /**
  3801. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3802. */
  3803. Vector4.prototype.add = function (otherVector) {
  3804. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3805. };
  3806. /**
  3807. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3808. * Returns the current Vector4.
  3809. */
  3810. Vector4.prototype.addToRef = function (otherVector, result) {
  3811. result.x = this.x + otherVector.x;
  3812. result.y = this.y + otherVector.y;
  3813. result.z = this.z + otherVector.z;
  3814. result.w = this.w + otherVector.w;
  3815. return this;
  3816. };
  3817. /**
  3818. * Subtract in place the given vector from the current Vector4.
  3819. * Returns the updated Vector4.
  3820. */
  3821. Vector4.prototype.subtractInPlace = function (otherVector) {
  3822. this.x -= otherVector.x;
  3823. this.y -= otherVector.y;
  3824. this.z -= otherVector.z;
  3825. this.w -= otherVector.w;
  3826. return this;
  3827. };
  3828. /**
  3829. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3830. */
  3831. Vector4.prototype.subtract = function (otherVector) {
  3832. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3833. };
  3834. /**
  3835. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3836. * Returns the current Vector4.
  3837. */
  3838. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3839. result.x = this.x - otherVector.x;
  3840. result.y = this.y - otherVector.y;
  3841. result.z = this.z - otherVector.z;
  3842. result.w = this.w - otherVector.w;
  3843. return this;
  3844. };
  3845. /**
  3846. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3847. */
  3848. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3849. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3850. };
  3851. /**
  3852. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3853. * Returns the current Vector4.
  3854. */
  3855. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3856. result.x = this.x - x;
  3857. result.y = this.y - y;
  3858. result.z = this.z - z;
  3859. result.w = this.w - w;
  3860. return this;
  3861. };
  3862. /**
  3863. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3864. */
  3865. Vector4.prototype.negate = function () {
  3866. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3867. };
  3868. /**
  3869. * Multiplies the current Vector4 coordinates by scale (float).
  3870. * Returns the updated Vector4.
  3871. */
  3872. Vector4.prototype.scaleInPlace = function (scale) {
  3873. this.x *= scale;
  3874. this.y *= scale;
  3875. this.z *= scale;
  3876. this.w *= scale;
  3877. return this;
  3878. };
  3879. /**
  3880. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3881. */
  3882. Vector4.prototype.scale = function (scale) {
  3883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3884. };
  3885. /**
  3886. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3887. * Returns the current Vector4.
  3888. */
  3889. Vector4.prototype.scaleToRef = function (scale, result) {
  3890. result.x = this.x * scale;
  3891. result.y = this.y * scale;
  3892. result.z = this.z * scale;
  3893. result.w = this.w * scale;
  3894. return this;
  3895. };
  3896. /**
  3897. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3898. * @param scale defines the scale factor
  3899. * @param result defines the Vector4 object where to store the result
  3900. * @returns the unmodified current Vector4
  3901. */
  3902. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3903. result.x += this.x * scale;
  3904. result.y += this.y * scale;
  3905. result.z += this.z * scale;
  3906. result.w += this.w * scale;
  3907. return this;
  3908. };
  3909. /**
  3910. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3911. */
  3912. Vector4.prototype.equals = function (otherVector) {
  3913. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3914. };
  3915. /**
  3916. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3917. */
  3918. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3919. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3920. return otherVector
  3921. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3922. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3923. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3924. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3925. };
  3926. /**
  3927. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3928. */
  3929. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3930. return this.x === x && this.y === y && this.z === z && this.w === w;
  3931. };
  3932. /**
  3933. * Multiplies in place the current Vector4 by the given one.
  3934. * Returns the updated Vector4.
  3935. */
  3936. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3937. this.x *= otherVector.x;
  3938. this.y *= otherVector.y;
  3939. this.z *= otherVector.z;
  3940. this.w *= otherVector.w;
  3941. return this;
  3942. };
  3943. /**
  3944. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3945. */
  3946. Vector4.prototype.multiply = function (otherVector) {
  3947. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3948. };
  3949. /**
  3950. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3951. * Returns the current Vector4.
  3952. */
  3953. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3954. result.x = this.x * otherVector.x;
  3955. result.y = this.y * otherVector.y;
  3956. result.z = this.z * otherVector.z;
  3957. result.w = this.w * otherVector.w;
  3958. return this;
  3959. };
  3960. /**
  3961. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3962. */
  3963. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3964. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3965. };
  3966. /**
  3967. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3968. */
  3969. Vector4.prototype.divide = function (otherVector) {
  3970. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3971. };
  3972. /**
  3973. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3974. * Returns the current Vector4.
  3975. */
  3976. Vector4.prototype.divideToRef = function (otherVector, result) {
  3977. result.x = this.x / otherVector.x;
  3978. result.y = this.y / otherVector.y;
  3979. result.z = this.z / otherVector.z;
  3980. result.w = this.w / otherVector.w;
  3981. return this;
  3982. };
  3983. /**
  3984. * Divides the current Vector3 coordinates by the given ones.
  3985. * @returns the updated Vector3.
  3986. */
  3987. Vector4.prototype.divideInPlace = function (otherVector) {
  3988. return this.divideToRef(otherVector, this);
  3989. };
  3990. /**
  3991. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3992. * @param other defines the second operand
  3993. * @returns the current updated Vector4
  3994. */
  3995. Vector4.prototype.minimizeInPlace = function (other) {
  3996. if (other.x < this.x)
  3997. this.x = other.x;
  3998. if (other.y < this.y)
  3999. this.y = other.y;
  4000. if (other.z < this.z)
  4001. this.z = other.z;
  4002. if (other.w < this.w)
  4003. this.w = other.w;
  4004. return this;
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.maximizeInPlace = function (other) {
  4012. if (other.x > this.x)
  4013. this.x = other.x;
  4014. if (other.y > this.y)
  4015. this.y = other.y;
  4016. if (other.z > this.z)
  4017. this.z = other.z;
  4018. if (other.w > this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. // Properties
  4023. /**
  4024. * Returns the Vector4 length (float).
  4025. */
  4026. Vector4.prototype.length = function () {
  4027. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4028. };
  4029. /**
  4030. * Returns the Vector4 squared length (float).
  4031. */
  4032. Vector4.prototype.lengthSquared = function () {
  4033. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4034. };
  4035. // Methods
  4036. /**
  4037. * Normalizes in place the Vector4.
  4038. * Returns the updated Vector4.
  4039. */
  4040. Vector4.prototype.normalize = function () {
  4041. var len = this.length();
  4042. if (len === 0)
  4043. return this;
  4044. var num = 1.0 / len;
  4045. this.x *= num;
  4046. this.y *= num;
  4047. this.z *= num;
  4048. this.w *= num;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4053. */
  4054. Vector4.prototype.toVector3 = function () {
  4055. return new Vector3(this.x, this.y, this.z);
  4056. };
  4057. /**
  4058. * Returns a new Vector4 copied from the current one.
  4059. */
  4060. Vector4.prototype.clone = function () {
  4061. return new Vector4(this.x, this.y, this.z, this.w);
  4062. };
  4063. /**
  4064. * Updates the current Vector4 with the given one coordinates.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.copyFrom = function (source) {
  4068. this.x = source.x;
  4069. this.y = source.y;
  4070. this.z = source.z;
  4071. this.w = source.w;
  4072. return this;
  4073. };
  4074. /**
  4075. * Updates the current Vector4 coordinates with the given floats.
  4076. * Returns the updated Vector4.
  4077. */
  4078. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4079. this.x = x;
  4080. this.y = y;
  4081. this.z = z;
  4082. this.w = w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Updates the current Vector4 coordinates with the given floats.
  4087. * Returns the updated Vector4.
  4088. */
  4089. Vector4.prototype.set = function (x, y, z, w) {
  4090. return this.copyFromFloats(x, y, z, w);
  4091. };
  4092. // Statics
  4093. /**
  4094. * Returns a new Vector4 set from the starting index of the given array.
  4095. */
  4096. Vector4.FromArray = function (array, offset) {
  4097. if (!offset) {
  4098. offset = 0;
  4099. }
  4100. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4101. };
  4102. /**
  4103. * Updates the given vector "result" from the starting index of the given array.
  4104. */
  4105. Vector4.FromArrayToRef = function (array, offset, result) {
  4106. result.x = array[offset];
  4107. result.y = array[offset + 1];
  4108. result.z = array[offset + 2];
  4109. result.w = array[offset + 3];
  4110. };
  4111. /**
  4112. * Updates the given vector "result" from the starting index of the given Float32Array.
  4113. */
  4114. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4115. Vector4.FromArrayToRef(array, offset, result);
  4116. };
  4117. /**
  4118. * Updates the given vector "result" coordinates from the given floats.
  4119. */
  4120. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4121. result.x = x;
  4122. result.y = y;
  4123. result.z = z;
  4124. result.w = w;
  4125. };
  4126. /**
  4127. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4128. */
  4129. Vector4.Zero = function () {
  4130. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4131. };
  4132. /**
  4133. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4134. */
  4135. Vector4.One = function () {
  4136. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4137. };
  4138. /**
  4139. * Returns a new normalized Vector4 from the given one.
  4140. */
  4141. Vector4.Normalize = function (vector) {
  4142. var result = Vector4.Zero();
  4143. Vector4.NormalizeToRef(vector, result);
  4144. return result;
  4145. };
  4146. /**
  4147. * Updates the given vector "result" from the normalization of the given one.
  4148. */
  4149. Vector4.NormalizeToRef = function (vector, result) {
  4150. result.copyFrom(vector);
  4151. result.normalize();
  4152. };
  4153. Vector4.Minimize = function (left, right) {
  4154. var min = left.clone();
  4155. min.minimizeInPlace(right);
  4156. return min;
  4157. };
  4158. Vector4.Maximize = function (left, right) {
  4159. var max = left.clone();
  4160. max.maximizeInPlace(right);
  4161. return max;
  4162. };
  4163. /**
  4164. * Returns the distance (float) between the vectors "value1" and "value2".
  4165. */
  4166. Vector4.Distance = function (value1, value2) {
  4167. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4168. };
  4169. /**
  4170. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4171. */
  4172. Vector4.DistanceSquared = function (value1, value2) {
  4173. var x = value1.x - value2.x;
  4174. var y = value1.y - value2.y;
  4175. var z = value1.z - value2.z;
  4176. var w = value1.w - value2.w;
  4177. return (x * x) + (y * y) + (z * z) + (w * w);
  4178. };
  4179. /**
  4180. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Center = function (value1, value2) {
  4183. var center = value1.add(value2);
  4184. center.scaleInPlace(0.5);
  4185. return center;
  4186. };
  4187. /**
  4188. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4189. * This methods computes transformed normalized direction vectors only.
  4190. */
  4191. Vector4.TransformNormal = function (vector, transformation) {
  4192. var result = Vector4.Zero();
  4193. Vector4.TransformNormalToRef(vector, transformation, result);
  4194. return result;
  4195. };
  4196. /**
  4197. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4198. * This methods computes transformed normalized direction vectors only.
  4199. */
  4200. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4201. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4202. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4203. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4204. result.x = x;
  4205. result.y = y;
  4206. result.z = z;
  4207. result.w = vector.w;
  4208. };
  4209. /**
  4210. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4211. * This methods computes transformed normalized direction vectors only.
  4212. */
  4213. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4214. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4215. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4216. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4217. result.w = w;
  4218. };
  4219. return Vector4;
  4220. }());
  4221. BABYLON.Vector4 = Vector4;
  4222. var Size = /** @class */ (function () {
  4223. /**
  4224. * Creates a Size object from the given width and height (floats).
  4225. */
  4226. function Size(width, height) {
  4227. this.width = width;
  4228. this.height = height;
  4229. }
  4230. // Returns a string with the Size width and height.
  4231. Size.prototype.toString = function () {
  4232. return "{W: " + this.width + ", H: " + this.height + "}";
  4233. };
  4234. /**
  4235. * Returns the string "Size"
  4236. */
  4237. Size.prototype.getClassName = function () {
  4238. return "Size";
  4239. };
  4240. /**
  4241. * Returns the Size hash code.
  4242. */
  4243. Size.prototype.getHashCode = function () {
  4244. var hash = this.width || 0;
  4245. hash = (hash * 397) ^ (this.height || 0);
  4246. return hash;
  4247. };
  4248. /**
  4249. * Updates the current size from the given one.
  4250. * Returns the updated Size.
  4251. */
  4252. Size.prototype.copyFrom = function (src) {
  4253. this.width = src.width;
  4254. this.height = src.height;
  4255. };
  4256. /**
  4257. * Updates in place the current Size from the given floats.
  4258. * Returns the updated Size.
  4259. */
  4260. Size.prototype.copyFromFloats = function (width, height) {
  4261. this.width = width;
  4262. this.height = height;
  4263. return this;
  4264. };
  4265. /**
  4266. * Updates in place the current Size from the given floats.
  4267. * Returns the updated Size.
  4268. */
  4269. Size.prototype.set = function (width, height) {
  4270. return this.copyFromFloats(width, height);
  4271. };
  4272. /**
  4273. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4274. */
  4275. Size.prototype.multiplyByFloats = function (w, h) {
  4276. return new Size(this.width * w, this.height * h);
  4277. };
  4278. /**
  4279. * Returns a new Size copied from the given one.
  4280. */
  4281. Size.prototype.clone = function () {
  4282. return new Size(this.width, this.height);
  4283. };
  4284. /**
  4285. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4286. */
  4287. Size.prototype.equals = function (other) {
  4288. if (!other) {
  4289. return false;
  4290. }
  4291. return (this.width === other.width) && (this.height === other.height);
  4292. };
  4293. Object.defineProperty(Size.prototype, "surface", {
  4294. /**
  4295. * Returns the surface of the Size : width * height (float).
  4296. */
  4297. get: function () {
  4298. return this.width * this.height;
  4299. },
  4300. enumerable: true,
  4301. configurable: true
  4302. });
  4303. /**
  4304. * Returns a new Size set to (0.0, 0.0)
  4305. */
  4306. Size.Zero = function () {
  4307. return new Size(0.0, 0.0);
  4308. };
  4309. /**
  4310. * Returns a new Size set as the addition result of the current Size and the given one.
  4311. */
  4312. Size.prototype.add = function (otherSize) {
  4313. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4314. return r;
  4315. };
  4316. /**
  4317. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4318. */
  4319. Size.prototype.subtract = function (otherSize) {
  4320. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4321. return r;
  4322. };
  4323. /**
  4324. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4325. */
  4326. Size.Lerp = function (start, end, amount) {
  4327. var w = start.width + ((end.width - start.width) * amount);
  4328. var h = start.height + ((end.height - start.height) * amount);
  4329. return new Size(w, h);
  4330. };
  4331. return Size;
  4332. }());
  4333. BABYLON.Size = Size;
  4334. /**
  4335. * Class used to store quaternion data
  4336. * @see https://en.wikipedia.org/wiki/Quaternion
  4337. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4338. */
  4339. var Quaternion = /** @class */ (function () {
  4340. /**
  4341. * Creates a new Quaternion from the given floats
  4342. * @param x defines the first component (0 by default)
  4343. * @param y defines the second component (0 by default)
  4344. * @param z defines the third component (0 by default)
  4345. * @param w defines the fourth component (1.0 by default)
  4346. */
  4347. function Quaternion(
  4348. /** defines the first component (0 by default) */
  4349. x,
  4350. /** defines the second component (0 by default) */
  4351. y,
  4352. /** defines the third component (0 by default) */
  4353. z,
  4354. /** defines the fourth component (1.0 by default) */
  4355. w) {
  4356. if (x === void 0) { x = 0.0; }
  4357. if (y === void 0) { y = 0.0; }
  4358. if (z === void 0) { z = 0.0; }
  4359. if (w === void 0) { w = 1.0; }
  4360. this.x = x;
  4361. this.y = y;
  4362. this.z = z;
  4363. this.w = w;
  4364. }
  4365. /**
  4366. * Gets a string representation for the current quaternion
  4367. * @returns a string with the Quaternion coordinates
  4368. */
  4369. Quaternion.prototype.toString = function () {
  4370. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4371. };
  4372. /**
  4373. * Gets the class name of the quaternion
  4374. * @returns the string "Quaternion"
  4375. */
  4376. Quaternion.prototype.getClassName = function () {
  4377. return "Quaternion";
  4378. };
  4379. /**
  4380. * Gets a hash code for this quaternion
  4381. * @returns the quaternion hash code
  4382. */
  4383. Quaternion.prototype.getHashCode = function () {
  4384. var hash = this.x || 0;
  4385. hash = (hash * 397) ^ (this.y || 0);
  4386. hash = (hash * 397) ^ (this.z || 0);
  4387. hash = (hash * 397) ^ (this.w || 0);
  4388. return hash;
  4389. };
  4390. /**
  4391. * Copy the quaternion to an array
  4392. * @returns a new array populated with 4 elements from the quaternion coordinates
  4393. */
  4394. Quaternion.prototype.asArray = function () {
  4395. return [this.x, this.y, this.z, this.w];
  4396. };
  4397. /**
  4398. * Check if two quaternions are equals
  4399. * @param otherQuaternion defines the second operand
  4400. * @return true if the current quaternion and the given one coordinates are strictly equals
  4401. */
  4402. Quaternion.prototype.equals = function (otherQuaternion) {
  4403. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4404. };
  4405. /**
  4406. * Clone the current quaternion
  4407. * @returns a new quaternion copied from the current one
  4408. */
  4409. Quaternion.prototype.clone = function () {
  4410. return new Quaternion(this.x, this.y, this.z, this.w);
  4411. };
  4412. /**
  4413. * Copy a quaternion to the current one
  4414. * @param other defines the other quaternion
  4415. * @returns the updated current quaternion
  4416. */
  4417. Quaternion.prototype.copyFrom = function (other) {
  4418. this.x = other.x;
  4419. this.y = other.y;
  4420. this.z = other.z;
  4421. this.w = other.w;
  4422. return this;
  4423. };
  4424. /**
  4425. * Updates the current quaternion with the given float coordinates
  4426. * @param x defines the x coordinate
  4427. * @param y defines the y coordinate
  4428. * @param z defines the z coordinate
  4429. * @param w defines the w coordinate
  4430. * @returns the updated current quaternion
  4431. */
  4432. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4433. this.x = x;
  4434. this.y = y;
  4435. this.z = z;
  4436. this.w = w;
  4437. return this;
  4438. };
  4439. /**
  4440. * Updates the current quaternion from the given float coordinates
  4441. * @param x defines the x coordinate
  4442. * @param y defines the y coordinate
  4443. * @param z defines the z coordinate
  4444. * @param w defines the w coordinate
  4445. * @returns the updated current quaternion
  4446. */
  4447. Quaternion.prototype.set = function (x, y, z, w) {
  4448. return this.copyFromFloats(x, y, z, w);
  4449. };
  4450. /**
  4451. * Adds two quaternions
  4452. * @param other defines the second operand
  4453. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4454. */
  4455. Quaternion.prototype.add = function (other) {
  4456. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4457. };
  4458. /**
  4459. * Add a quaternion to the current one
  4460. * @param other defines the quaternion to add
  4461. * @returns the current quaternion
  4462. */
  4463. Quaternion.prototype.addInPlace = function (other) {
  4464. this.x += other.x;
  4465. this.y += other.y;
  4466. this.z += other.z;
  4467. this.w += other.w;
  4468. return this;
  4469. };
  4470. /**
  4471. * Subtract two quaternions
  4472. * @param other defines the second operand
  4473. * @returns a new quaternion as the subtraction result of the given one from the current one
  4474. */
  4475. Quaternion.prototype.subtract = function (other) {
  4476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4477. };
  4478. /**
  4479. * Multiplies the current quaternion by a scale factor
  4480. * @param value defines the scale factor
  4481. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4482. */
  4483. Quaternion.prototype.scale = function (value) {
  4484. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4485. };
  4486. /**
  4487. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4488. * @param scale defines the scale factor
  4489. * @param result defines the Quaternion object where to store the result
  4490. * @returns the unmodified current quaternion
  4491. */
  4492. Quaternion.prototype.scaleToRef = function (scale, result) {
  4493. result.x = this.x * scale;
  4494. result.y = this.y * scale;
  4495. result.z = this.z * scale;
  4496. result.w = this.w * scale;
  4497. return this;
  4498. };
  4499. /**
  4500. * Multiplies in place the current quaternion by a scale factor
  4501. * @param value defines the scale factor
  4502. * @returns the current modified quaternion
  4503. */
  4504. Quaternion.prototype.scaleInPlace = function (value) {
  4505. this.x *= value;
  4506. this.y *= value;
  4507. this.z *= value;
  4508. this.w *= value;
  4509. return this;
  4510. };
  4511. /**
  4512. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4513. * @param scale defines the scale factor
  4514. * @param result defines the Quaternion object where to store the result
  4515. * @returns the unmodified current quaternion
  4516. */
  4517. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4518. result.x += this.x * scale;
  4519. result.y += this.y * scale;
  4520. result.z += this.z * scale;
  4521. result.w += this.w * scale;
  4522. return this;
  4523. };
  4524. /**
  4525. * Multiplies two quaternions
  4526. * @param q1 defines the second operand
  4527. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4528. */
  4529. Quaternion.prototype.multiply = function (q1) {
  4530. var result = new Quaternion(0, 0, 0, 1.0);
  4531. this.multiplyToRef(q1, result);
  4532. return result;
  4533. };
  4534. /**
  4535. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4536. * @param q1 defines the second operand
  4537. * @param result defines the target quaternion
  4538. * @returns the current quaternion
  4539. */
  4540. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4541. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4542. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4543. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4544. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4545. result.copyFromFloats(x, y, z, w);
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4550. * @param q1 defines the second operand
  4551. * @returns the currentupdated quaternion
  4552. */
  4553. Quaternion.prototype.multiplyInPlace = function (q1) {
  4554. this.multiplyToRef(q1, this);
  4555. return this;
  4556. };
  4557. /**
  4558. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4559. * @param ref defines the target quaternion
  4560. * @returns the current quaternion
  4561. */
  4562. Quaternion.prototype.conjugateToRef = function (ref) {
  4563. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4564. return this;
  4565. };
  4566. /**
  4567. * Conjugates in place (1-q) the current quaternion
  4568. * @returns the current updated quaternion
  4569. */
  4570. Quaternion.prototype.conjugateInPlace = function () {
  4571. this.x *= -1;
  4572. this.y *= -1;
  4573. this.z *= -1;
  4574. return this;
  4575. };
  4576. /**
  4577. * Conjugates in place (1-q) the current quaternion
  4578. * @returns a new quaternion
  4579. */
  4580. Quaternion.prototype.conjugate = function () {
  4581. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4582. return result;
  4583. };
  4584. /**
  4585. * Gets length of current quaternion
  4586. * @returns the quaternion length (float)
  4587. */
  4588. Quaternion.prototype.length = function () {
  4589. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4590. };
  4591. /**
  4592. * Normalize in place the current quaternion
  4593. * @returns the current updated quaternion
  4594. */
  4595. Quaternion.prototype.normalize = function () {
  4596. var length = 1.0 / this.length();
  4597. this.x *= length;
  4598. this.y *= length;
  4599. this.z *= length;
  4600. this.w *= length;
  4601. return this;
  4602. };
  4603. /**
  4604. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4605. * @param order is a reserved parameter and is ignore for now
  4606. * @returns a new Vector3 containing the Euler angles
  4607. */
  4608. Quaternion.prototype.toEulerAngles = function (order) {
  4609. if (order === void 0) { order = "YZX"; }
  4610. var result = Vector3.Zero();
  4611. this.toEulerAnglesToRef(result, order);
  4612. return result;
  4613. };
  4614. /**
  4615. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4616. * @param result defines the vector which will be filled with the Euler angles
  4617. * @param order is a reserved parameter and is ignore for now
  4618. * @returns the current unchanged quaternion
  4619. */
  4620. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4621. if (order === void 0) { order = "YZX"; }
  4622. var qz = this.z;
  4623. var qx = this.x;
  4624. var qy = this.y;
  4625. var qw = this.w;
  4626. var sqw = qw * qw;
  4627. var sqz = qz * qz;
  4628. var sqx = qx * qx;
  4629. var sqy = qy * qy;
  4630. var zAxisY = qy * qz - qx * qw;
  4631. var limit = .4999999;
  4632. if (zAxisY < -limit) {
  4633. result.y = 2 * Math.atan2(qy, qw);
  4634. result.x = Math.PI / 2;
  4635. result.z = 0;
  4636. }
  4637. else if (zAxisY > limit) {
  4638. result.y = 2 * Math.atan2(qy, qw);
  4639. result.x = -Math.PI / 2;
  4640. result.z = 0;
  4641. }
  4642. else {
  4643. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4644. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4645. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4646. }
  4647. return this;
  4648. };
  4649. /**
  4650. * Updates the given rotation matrix with the current quaternion values
  4651. * @param result defines the target matrix
  4652. * @returns the current unchanged quaternion
  4653. */
  4654. Quaternion.prototype.toRotationMatrix = function (result) {
  4655. var xx = this.x * this.x;
  4656. var yy = this.y * this.y;
  4657. var zz = this.z * this.z;
  4658. var xy = this.x * this.y;
  4659. var zw = this.z * this.w;
  4660. var zx = this.z * this.x;
  4661. var yw = this.y * this.w;
  4662. var yz = this.y * this.z;
  4663. var xw = this.x * this.w;
  4664. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4665. result.m[1] = 2.0 * (xy + zw);
  4666. result.m[2] = 2.0 * (zx - yw);
  4667. result.m[3] = 0;
  4668. result.m[4] = 2.0 * (xy - zw);
  4669. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4670. result.m[6] = 2.0 * (yz + xw);
  4671. result.m[7] = 0;
  4672. result.m[8] = 2.0 * (zx + yw);
  4673. result.m[9] = 2.0 * (yz - xw);
  4674. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4675. result.m[11] = 0;
  4676. result.m[12] = 0;
  4677. result.m[13] = 0;
  4678. result.m[14] = 0;
  4679. result.m[15] = 1.0;
  4680. result._markAsUpdated();
  4681. return this;
  4682. };
  4683. /**
  4684. * Updates the current quaternion from the given rotation matrix values
  4685. * @param matrix defines the source matrix
  4686. * @returns the current updated quaternion
  4687. */
  4688. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4689. Quaternion.FromRotationMatrixToRef(matrix, this);
  4690. return this;
  4691. };
  4692. // Statics
  4693. /**
  4694. * Creates a new quaternion from a rotation matrix
  4695. * @param matrix defines the source matrix
  4696. * @returns a new quaternion created from the given rotation matrix values
  4697. */
  4698. Quaternion.FromRotationMatrix = function (matrix) {
  4699. var result = new Quaternion();
  4700. Quaternion.FromRotationMatrixToRef(matrix, result);
  4701. return result;
  4702. };
  4703. /**
  4704. * Updates the given quaternion with the given rotation matrix values
  4705. * @param matrix defines the source matrix
  4706. * @param result defines the target quaternion
  4707. */
  4708. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4709. var data = matrix.m;
  4710. var m11 = data[0], m12 = data[4], m13 = data[8];
  4711. var m21 = data[1], m22 = data[5], m23 = data[9];
  4712. var m31 = data[2], m32 = data[6], m33 = data[10];
  4713. var trace = m11 + m22 + m33;
  4714. var s;
  4715. if (trace > 0) {
  4716. s = 0.5 / Math.sqrt(trace + 1.0);
  4717. result.w = 0.25 / s;
  4718. result.x = (m32 - m23) * s;
  4719. result.y = (m13 - m31) * s;
  4720. result.z = (m21 - m12) * s;
  4721. }
  4722. else if (m11 > m22 && m11 > m33) {
  4723. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4724. result.w = (m32 - m23) / s;
  4725. result.x = 0.25 * s;
  4726. result.y = (m12 + m21) / s;
  4727. result.z = (m13 + m31) / s;
  4728. }
  4729. else if (m22 > m33) {
  4730. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4731. result.w = (m13 - m31) / s;
  4732. result.x = (m12 + m21) / s;
  4733. result.y = 0.25 * s;
  4734. result.z = (m23 + m32) / s;
  4735. }
  4736. else {
  4737. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4738. result.w = (m21 - m12) / s;
  4739. result.x = (m13 + m31) / s;
  4740. result.y = (m23 + m32) / s;
  4741. result.z = 0.25 * s;
  4742. }
  4743. };
  4744. /**
  4745. * Returns the dot product (float) between the quaternions "left" and "right"
  4746. * @param left defines the left operand
  4747. * @param right defines the right operand
  4748. * @returns the dot product
  4749. */
  4750. Quaternion.Dot = function (left, right) {
  4751. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4752. };
  4753. /**
  4754. * Checks if the two quaternions are close to each other
  4755. * @param quat0 defines the first quaternion to check
  4756. * @param quat1 defines the second quaternion to check
  4757. * @returns true if the two quaternions are close to each other
  4758. */
  4759. Quaternion.AreClose = function (quat0, quat1) {
  4760. var dot = Quaternion.Dot(quat0, quat1);
  4761. return dot >= 0;
  4762. };
  4763. /**
  4764. * Creates an empty quaternion
  4765. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4766. */
  4767. Quaternion.Zero = function () {
  4768. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4769. };
  4770. /**
  4771. * Inverse a given quaternion
  4772. * @param q defines the source quaternion
  4773. * @returns a new quaternion as the inverted current quaternion
  4774. */
  4775. Quaternion.Inverse = function (q) {
  4776. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4777. };
  4778. /**
  4779. * Creates an identity quaternion
  4780. * @returns the identity quaternion
  4781. */
  4782. Quaternion.Identity = function () {
  4783. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4784. };
  4785. /**
  4786. * Gets a boolean indicating if the given quaternion is identity
  4787. * @param quaternion defines the quaternion to check
  4788. * @returns true if the quaternion is identity
  4789. */
  4790. Quaternion.IsIdentity = function (quaternion) {
  4791. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4792. };
  4793. /**
  4794. * Creates a quaternion from a rotation around an axis
  4795. * @param axis defines the axis to use
  4796. * @param angle defines the angle to use
  4797. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4798. */
  4799. Quaternion.RotationAxis = function (axis, angle) {
  4800. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4801. };
  4802. /**
  4803. * Creates a rotation around an axis and stores it into the given quaternion
  4804. * @param axis defines the axis to use
  4805. * @param angle defines the angle to use
  4806. * @param result defines the target quaternion
  4807. * @returns the target quaternion
  4808. */
  4809. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4810. var sin = Math.sin(angle / 2);
  4811. axis.normalize();
  4812. result.w = Math.cos(angle / 2);
  4813. result.x = axis.x * sin;
  4814. result.y = axis.y * sin;
  4815. result.z = axis.z * sin;
  4816. return result;
  4817. };
  4818. /**
  4819. * Creates a new quaternion from data stored into an array
  4820. * @param array defines the data source
  4821. * @param offset defines the offset in the source array where the data starts
  4822. * @returns a new quaternion
  4823. */
  4824. Quaternion.FromArray = function (array, offset) {
  4825. if (!offset) {
  4826. offset = 0;
  4827. }
  4828. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4829. };
  4830. /**
  4831. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4832. * @param yaw defines the rotation around Y axis
  4833. * @param pitch defines the rotation around X axis
  4834. * @param roll defines the rotation around Z axis
  4835. * @returns the new quaternion
  4836. */
  4837. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4838. var q = new Quaternion();
  4839. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4840. return q;
  4841. };
  4842. /**
  4843. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4844. * @param yaw defines the rotation around Y axis
  4845. * @param pitch defines the rotation around X axis
  4846. * @param roll defines the rotation around Z axis
  4847. * @param result defines the target quaternion
  4848. */
  4849. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4850. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4851. var halfRoll = roll * 0.5;
  4852. var halfPitch = pitch * 0.5;
  4853. var halfYaw = yaw * 0.5;
  4854. var sinRoll = Math.sin(halfRoll);
  4855. var cosRoll = Math.cos(halfRoll);
  4856. var sinPitch = Math.sin(halfPitch);
  4857. var cosPitch = Math.cos(halfPitch);
  4858. var sinYaw = Math.sin(halfYaw);
  4859. var cosYaw = Math.cos(halfYaw);
  4860. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4861. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4862. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4863. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4864. };
  4865. /**
  4866. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4867. * @param alpha defines the rotation around first axis
  4868. * @param beta defines the rotation around second axis
  4869. * @param gamma defines the rotation around third axis
  4870. * @returns the new quaternion
  4871. */
  4872. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4873. var result = new Quaternion();
  4874. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4875. return result;
  4876. };
  4877. /**
  4878. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4879. * @param alpha defines the rotation around first axis
  4880. * @param beta defines the rotation around second axis
  4881. * @param gamma defines the rotation around third axis
  4882. * @param result defines the target quaternion
  4883. */
  4884. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4885. // Produces a quaternion from Euler angles in the z-x-z orientation
  4886. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4887. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4888. var halfBeta = beta * 0.5;
  4889. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4890. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4891. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4892. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4893. };
  4894. /**
  4895. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4896. * @param axis1 defines the first axis
  4897. * @param axis2 defines the second axis
  4898. * @param axis3 defines the third axis
  4899. * @returns the new quaternion
  4900. */
  4901. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4902. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4903. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4904. return quat;
  4905. };
  4906. /**
  4907. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4908. * @param axis1 defines the first axis
  4909. * @param axis2 defines the second axis
  4910. * @param axis3 defines the third axis
  4911. * @param ref defines the target quaternion
  4912. */
  4913. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4914. var rotMat = MathTmp.Matrix[0];
  4915. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4916. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4917. };
  4918. /**
  4919. * Interpolates between two quaternions
  4920. * @param left defines first quaternion
  4921. * @param right defines second quaternion
  4922. * @param amount defines the gradient to use
  4923. * @returns the new interpolated quaternion
  4924. */
  4925. Quaternion.Slerp = function (left, right, amount) {
  4926. var result = Quaternion.Identity();
  4927. Quaternion.SlerpToRef(left, right, amount, result);
  4928. return result;
  4929. };
  4930. /**
  4931. * Interpolates between two quaternions and stores it into a target quaternion
  4932. * @param left defines first quaternion
  4933. * @param right defines second quaternion
  4934. * @param amount defines the gradient to use
  4935. * @param result defines the target quaternion
  4936. */
  4937. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4938. var num2;
  4939. var num3;
  4940. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4941. var flag = false;
  4942. if (num4 < 0) {
  4943. flag = true;
  4944. num4 = -num4;
  4945. }
  4946. if (num4 > 0.999999) {
  4947. num3 = 1 - amount;
  4948. num2 = flag ? -amount : amount;
  4949. }
  4950. else {
  4951. var num5 = Math.acos(num4);
  4952. var num6 = (1.0 / Math.sin(num5));
  4953. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4954. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4955. }
  4956. result.x = (num3 * left.x) + (num2 * right.x);
  4957. result.y = (num3 * left.y) + (num2 * right.y);
  4958. result.z = (num3 * left.z) + (num2 * right.z);
  4959. result.w = (num3 * left.w) + (num2 * right.w);
  4960. };
  4961. /**
  4962. * Interpolate between two quaternions using Hermite interpolation
  4963. * @param value1 defines first quaternion
  4964. * @param tangent1 defines the incoming tangent
  4965. * @param value2 defines second quaternion
  4966. * @param tangent2 defines the outgoing tangent
  4967. * @param amount defines the target quaternion
  4968. * @returns the new interpolated quaternion
  4969. */
  4970. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4971. var squared = amount * amount;
  4972. var cubed = amount * squared;
  4973. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4974. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4975. var part3 = (cubed - (2.0 * squared)) + amount;
  4976. var part4 = cubed - squared;
  4977. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4978. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4979. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4980. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4981. return new Quaternion(x, y, z, w);
  4982. };
  4983. return Quaternion;
  4984. }());
  4985. BABYLON.Quaternion = Quaternion;
  4986. /**
  4987. * Class used to store matrix data (4x4)
  4988. */
  4989. var Matrix = /** @class */ (function () {
  4990. /**
  4991. * Creates an empty matrix (filled with zeros)
  4992. */
  4993. function Matrix() {
  4994. this._isIdentity = false;
  4995. this._isIdentityDirty = true;
  4996. /**
  4997. * Gets or sets the internal data of the matrix
  4998. */
  4999. this.m = new Float32Array(16);
  5000. this._markAsUpdated();
  5001. }
  5002. /** @hidden */
  5003. Matrix.prototype._markAsUpdated = function () {
  5004. this.updateFlag = Matrix._updateFlagSeed++;
  5005. this._isIdentityDirty = true;
  5006. };
  5007. // Properties
  5008. /**
  5009. * Check if the current matrix is indentity
  5010. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5011. * @returns true is the matrix is the identity matrix
  5012. */
  5013. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5014. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5015. if (this._isIdentityDirty) {
  5016. this._isIdentityDirty = false;
  5017. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5018. this._isIdentity = false;
  5019. }
  5020. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5021. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5022. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5023. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5024. this._isIdentity = false;
  5025. }
  5026. else {
  5027. this._isIdentity = true;
  5028. }
  5029. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5030. this._isIdentity = false;
  5031. }
  5032. }
  5033. return this._isIdentity;
  5034. };
  5035. /**
  5036. * Gets the determinant of the matrix
  5037. * @returns the matrix determinant
  5038. */
  5039. Matrix.prototype.determinant = function () {
  5040. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5041. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5042. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5043. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5044. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5045. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5046. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5047. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5048. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5049. };
  5050. // Methods
  5051. /**
  5052. * Returns the matrix as a Float32Array
  5053. * @returns the matrix underlying array
  5054. */
  5055. Matrix.prototype.toArray = function () {
  5056. return this.m;
  5057. };
  5058. /**
  5059. * Returns the matrix as a Float32Array
  5060. * @returns the matrix underlying array.
  5061. */
  5062. Matrix.prototype.asArray = function () {
  5063. return this.toArray();
  5064. };
  5065. /**
  5066. * Inverts the current matrix in place
  5067. * @returns the current inverted matrix
  5068. */
  5069. Matrix.prototype.invert = function () {
  5070. this.invertToRef(this);
  5071. return this;
  5072. };
  5073. /**
  5074. * Sets all the matrix elements to zero
  5075. * @returns the current matrix
  5076. */
  5077. Matrix.prototype.reset = function () {
  5078. for (var index = 0; index < 16; index++) {
  5079. this.m[index] = 0.0;
  5080. }
  5081. this._markAsUpdated();
  5082. return this;
  5083. };
  5084. /**
  5085. * Adds the current matrix with a second one
  5086. * @param other defines the matrix to add
  5087. * @returns a new matrix as the addition of the current matrix and the given one
  5088. */
  5089. Matrix.prototype.add = function (other) {
  5090. var result = new Matrix();
  5091. this.addToRef(other, result);
  5092. return result;
  5093. };
  5094. /**
  5095. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5096. * @param other defines the matrix to add
  5097. * @param result defines the target matrix
  5098. * @returns the current matrix
  5099. */
  5100. Matrix.prototype.addToRef = function (other, result) {
  5101. for (var index = 0; index < 16; index++) {
  5102. result.m[index] = this.m[index] + other.m[index];
  5103. }
  5104. result._markAsUpdated();
  5105. return this;
  5106. };
  5107. /**
  5108. * Adds in place the given matrix to the current matrix
  5109. * @param other defines the second operand
  5110. * @returns the current updated matrix
  5111. */
  5112. Matrix.prototype.addToSelf = function (other) {
  5113. for (var index = 0; index < 16; index++) {
  5114. this.m[index] += other.m[index];
  5115. }
  5116. this._markAsUpdated();
  5117. return this;
  5118. };
  5119. /**
  5120. * Sets the given matrix to the current inverted Matrix
  5121. * @param other defines the target matrix
  5122. * @returns the unmodified current matrix
  5123. */
  5124. Matrix.prototype.invertToRef = function (other) {
  5125. var l1 = this.m[0];
  5126. var l2 = this.m[1];
  5127. var l3 = this.m[2];
  5128. var l4 = this.m[3];
  5129. var l5 = this.m[4];
  5130. var l6 = this.m[5];
  5131. var l7 = this.m[6];
  5132. var l8 = this.m[7];
  5133. var l9 = this.m[8];
  5134. var l10 = this.m[9];
  5135. var l11 = this.m[10];
  5136. var l12 = this.m[11];
  5137. var l13 = this.m[12];
  5138. var l14 = this.m[13];
  5139. var l15 = this.m[14];
  5140. var l16 = this.m[15];
  5141. var l17 = (l11 * l16) - (l12 * l15);
  5142. var l18 = (l10 * l16) - (l12 * l14);
  5143. var l19 = (l10 * l15) - (l11 * l14);
  5144. var l20 = (l9 * l16) - (l12 * l13);
  5145. var l21 = (l9 * l15) - (l11 * l13);
  5146. var l22 = (l9 * l14) - (l10 * l13);
  5147. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5148. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5149. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5150. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5151. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5152. var l28 = (l7 * l16) - (l8 * l15);
  5153. var l29 = (l6 * l16) - (l8 * l14);
  5154. var l30 = (l6 * l15) - (l7 * l14);
  5155. var l31 = (l5 * l16) - (l8 * l13);
  5156. var l32 = (l5 * l15) - (l7 * l13);
  5157. var l33 = (l5 * l14) - (l6 * l13);
  5158. var l34 = (l7 * l12) - (l8 * l11);
  5159. var l35 = (l6 * l12) - (l8 * l10);
  5160. var l36 = (l6 * l11) - (l7 * l10);
  5161. var l37 = (l5 * l12) - (l8 * l9);
  5162. var l38 = (l5 * l11) - (l7 * l9);
  5163. var l39 = (l5 * l10) - (l6 * l9);
  5164. other.m[0] = l23 * l27;
  5165. other.m[4] = l24 * l27;
  5166. other.m[8] = l25 * l27;
  5167. other.m[12] = l26 * l27;
  5168. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5169. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5170. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5171. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5172. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5173. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5174. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5175. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5176. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5177. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5178. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5179. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5180. other._markAsUpdated();
  5181. return this;
  5182. };
  5183. /**
  5184. * Inserts the translation vector (using 3 floats) in the current matrix
  5185. * @param x defines the 1st component of the translation
  5186. * @param y defines the 2nd component of the translation
  5187. * @param z defines the 3rd component of the translation
  5188. * @returns the current updated matrix
  5189. */
  5190. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5191. this.m[12] = x;
  5192. this.m[13] = y;
  5193. this.m[14] = z;
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Inserts the translation vector in the current matrix
  5199. * @param vector3 defines the translation to insert
  5200. * @returns the current updated matrix
  5201. */
  5202. Matrix.prototype.setTranslation = function (vector3) {
  5203. this.m[12] = vector3.x;
  5204. this.m[13] = vector3.y;
  5205. this.m[14] = vector3.z;
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Gets the translation value of the current matrix
  5211. * @returns a new Vector3 as the extracted translation from the matrix
  5212. */
  5213. Matrix.prototype.getTranslation = function () {
  5214. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5215. };
  5216. /**
  5217. * Fill a Vector3 with the extracted translation from the matrix
  5218. * @param result defines the Vector3 where to store the translation
  5219. * @returns the current matrix
  5220. */
  5221. Matrix.prototype.getTranslationToRef = function (result) {
  5222. result.x = this.m[12];
  5223. result.y = this.m[13];
  5224. result.z = this.m[14];
  5225. return this;
  5226. };
  5227. /**
  5228. * Remove rotation and scaling part from the matrix
  5229. * @returns the updated matrix
  5230. */
  5231. Matrix.prototype.removeRotationAndScaling = function () {
  5232. this.setRowFromFloats(0, 1, 0, 0, 0);
  5233. this.setRowFromFloats(1, 0, 1, 0, 0);
  5234. this.setRowFromFloats(2, 0, 0, 1, 0);
  5235. return this;
  5236. };
  5237. /**
  5238. * Multiply two matrices
  5239. * @param other defines the second operand
  5240. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5241. */
  5242. Matrix.prototype.multiply = function (other) {
  5243. var result = new Matrix();
  5244. this.multiplyToRef(other, result);
  5245. return result;
  5246. };
  5247. /**
  5248. * Copy the current matrix from the given one
  5249. * @param other defines the source matrix
  5250. * @returns the current updated matrix
  5251. */
  5252. Matrix.prototype.copyFrom = function (other) {
  5253. for (var index = 0; index < 16; index++) {
  5254. this.m[index] = other.m[index];
  5255. }
  5256. this._markAsUpdated();
  5257. return this;
  5258. };
  5259. /**
  5260. * Populates the given array from the starting index with the current matrix values
  5261. * @param array defines the target array
  5262. * @param offset defines the offset in the target array where to start storing values
  5263. * @returns the current matrix
  5264. */
  5265. Matrix.prototype.copyToArray = function (array, offset) {
  5266. if (offset === void 0) { offset = 0; }
  5267. for (var index = 0; index < 16; index++) {
  5268. array[offset + index] = this.m[index];
  5269. }
  5270. return this;
  5271. };
  5272. /**
  5273. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5274. * @param other defines the second operand
  5275. * @param result defines the matrix where to store the multiplication
  5276. * @returns the current matrix
  5277. */
  5278. Matrix.prototype.multiplyToRef = function (other, result) {
  5279. this.multiplyToArray(other, result.m, 0);
  5280. result._markAsUpdated();
  5281. return this;
  5282. };
  5283. /**
  5284. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5285. * @param other defines the second operand
  5286. * @param result defines the array where to store the multiplication
  5287. * @param offset defines the offset in the target array where to start storing values
  5288. * @returns the current matrix
  5289. */
  5290. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5291. var tm0 = this.m[0];
  5292. var tm1 = this.m[1];
  5293. var tm2 = this.m[2];
  5294. var tm3 = this.m[3];
  5295. var tm4 = this.m[4];
  5296. var tm5 = this.m[5];
  5297. var tm6 = this.m[6];
  5298. var tm7 = this.m[7];
  5299. var tm8 = this.m[8];
  5300. var tm9 = this.m[9];
  5301. var tm10 = this.m[10];
  5302. var tm11 = this.m[11];
  5303. var tm12 = this.m[12];
  5304. var tm13 = this.m[13];
  5305. var tm14 = this.m[14];
  5306. var tm15 = this.m[15];
  5307. var om0 = other.m[0];
  5308. var om1 = other.m[1];
  5309. var om2 = other.m[2];
  5310. var om3 = other.m[3];
  5311. var om4 = other.m[4];
  5312. var om5 = other.m[5];
  5313. var om6 = other.m[6];
  5314. var om7 = other.m[7];
  5315. var om8 = other.m[8];
  5316. var om9 = other.m[9];
  5317. var om10 = other.m[10];
  5318. var om11 = other.m[11];
  5319. var om12 = other.m[12];
  5320. var om13 = other.m[13];
  5321. var om14 = other.m[14];
  5322. var om15 = other.m[15];
  5323. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5324. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5325. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5326. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5327. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5328. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5329. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5330. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5331. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5332. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5333. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5334. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5335. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5336. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5337. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5338. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5339. return this;
  5340. };
  5341. /**
  5342. * Check equality between this matrix and a second one
  5343. * @param value defines the second matrix to compare
  5344. * @returns true is the current matrix and the given one values are strictly equal
  5345. */
  5346. Matrix.prototype.equals = function (value) {
  5347. return value &&
  5348. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5349. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5350. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5351. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5352. };
  5353. /**
  5354. * Clone the current matrix
  5355. * @returns a new matrix from the current matrix
  5356. */
  5357. Matrix.prototype.clone = function () {
  5358. 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]);
  5359. };
  5360. /**
  5361. * Returns the name of the current matrix class
  5362. * @returns the string "Matrix"
  5363. */
  5364. Matrix.prototype.getClassName = function () {
  5365. return "Matrix";
  5366. };
  5367. /**
  5368. * Gets the hash code of the current matrix
  5369. * @returns the hash code
  5370. */
  5371. Matrix.prototype.getHashCode = function () {
  5372. var hash = this.m[0] || 0;
  5373. for (var i = 1; i < 16; i++) {
  5374. hash = (hash * 397) ^ (this.m[i] || 0);
  5375. }
  5376. return hash;
  5377. };
  5378. /**
  5379. * Decomposes the current Matrix into a translation, rotation and scaling components
  5380. * @param scale defines the scale vector3 given as a reference to update
  5381. * @param rotation defines the rotation quaternion given as a reference to update
  5382. * @param translation defines the translation vector3 given as a reference to update
  5383. * @returns true if operation was successful
  5384. */
  5385. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5386. if (translation) {
  5387. translation.x = this.m[12];
  5388. translation.y = this.m[13];
  5389. translation.z = this.m[14];
  5390. }
  5391. scale = scale || MathTmp.Vector3[0];
  5392. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5393. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5394. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5395. if (this.determinant() <= 0) {
  5396. scale.y *= -1;
  5397. }
  5398. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5399. if (rotation) {
  5400. rotation.x = 0;
  5401. rotation.y = 0;
  5402. rotation.z = 0;
  5403. rotation.w = 1;
  5404. }
  5405. return false;
  5406. }
  5407. if (rotation) {
  5408. 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]);
  5409. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5410. }
  5411. return true;
  5412. };
  5413. /**
  5414. * Gets specific row of the matrix
  5415. * @param index defines the number of the row to get
  5416. * @returns the index-th row of the current matrix as a new Vector4
  5417. */
  5418. Matrix.prototype.getRow = function (index) {
  5419. if (index < 0 || index > 3) {
  5420. return null;
  5421. }
  5422. var i = index * 4;
  5423. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5424. };
  5425. /**
  5426. * Sets the index-th row of the current matrix to the vector4 values
  5427. * @param index defines the number of the row to set
  5428. * @param row defines the target vector4
  5429. * @returns the updated current matrix
  5430. */
  5431. Matrix.prototype.setRow = function (index, row) {
  5432. if (index < 0 || index > 3) {
  5433. return this;
  5434. }
  5435. var i = index * 4;
  5436. this.m[i + 0] = row.x;
  5437. this.m[i + 1] = row.y;
  5438. this.m[i + 2] = row.z;
  5439. this.m[i + 3] = row.w;
  5440. this._markAsUpdated();
  5441. return this;
  5442. };
  5443. /**
  5444. * Compute the transpose of the matrix
  5445. * @returns the new transposed matrix
  5446. */
  5447. Matrix.prototype.transpose = function () {
  5448. return Matrix.Transpose(this);
  5449. };
  5450. /**
  5451. * Compute the transpose of the matrix and store it in a given matrix
  5452. * @param result defines the target matrix
  5453. * @returns the current matrix
  5454. */
  5455. Matrix.prototype.transposeToRef = function (result) {
  5456. Matrix.TransposeToRef(this, result);
  5457. return this;
  5458. };
  5459. /**
  5460. * Sets the index-th row of the current matrix with the given 4 x float values
  5461. * @param index defines the row index
  5462. * @param x defines the x component to set
  5463. * @param y defines the y component to set
  5464. * @param z defines the z component to set
  5465. * @param w defines the w component to set
  5466. * @returns the updated current matrix
  5467. */
  5468. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5469. if (index < 0 || index > 3) {
  5470. return this;
  5471. }
  5472. var i = index * 4;
  5473. this.m[i + 0] = x;
  5474. this.m[i + 1] = y;
  5475. this.m[i + 2] = z;
  5476. this.m[i + 3] = w;
  5477. this._markAsUpdated();
  5478. return this;
  5479. };
  5480. /**
  5481. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5482. * @param scale defines the scale factor
  5483. * @returns a new matrix
  5484. */
  5485. Matrix.prototype.scale = function (scale) {
  5486. var result = new Matrix();
  5487. this.scaleToRef(scale, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Scale the current matrix values by a factor to a given result matrix
  5492. * @param scale defines the scale factor
  5493. * @param result defines the matrix to store the result
  5494. * @returns the current matrix
  5495. */
  5496. Matrix.prototype.scaleToRef = function (scale, result) {
  5497. for (var index = 0; index < 16; index++) {
  5498. result.m[index] = this.m[index] * scale;
  5499. }
  5500. result._markAsUpdated();
  5501. return this;
  5502. };
  5503. /**
  5504. * Scale the current matrix values by a factor and add the result to a given matrix
  5505. * @param scale defines the scale factor
  5506. * @param result defines the Matrix to store the result
  5507. * @returns the current matrix
  5508. */
  5509. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5510. for (var index = 0; index < 16; index++) {
  5511. result.m[index] += this.m[index] * scale;
  5512. }
  5513. result._markAsUpdated();
  5514. return this;
  5515. };
  5516. /**
  5517. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5518. * @param ref matrix to store the result
  5519. */
  5520. Matrix.prototype.toNormalMatrix = function (ref) {
  5521. this.invertToRef(ref);
  5522. ref.transpose();
  5523. var m = ref.m;
  5524. 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);
  5525. };
  5526. /**
  5527. * Gets only rotation part of the current matrix
  5528. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5529. */
  5530. Matrix.prototype.getRotationMatrix = function () {
  5531. var result = Matrix.Identity();
  5532. this.getRotationMatrixToRef(result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5537. * @param result defines the target matrix to store data to
  5538. * @returns the current matrix
  5539. */
  5540. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5541. var m = this.m;
  5542. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5543. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5544. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5545. if (this.determinant() <= 0) {
  5546. sy *= -1;
  5547. }
  5548. if (sx === 0 || sy === 0 || sz === 0) {
  5549. Matrix.IdentityToRef(result);
  5550. }
  5551. else {
  5552. 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);
  5553. }
  5554. return this;
  5555. };
  5556. // Statics
  5557. /**
  5558. * Creates a matrix from an array
  5559. * @param array defines the source array
  5560. * @param offset defines an offset in the source array
  5561. * @returns a new Matrix set from the starting index of the given array
  5562. */
  5563. Matrix.FromArray = function (array, offset) {
  5564. var result = new Matrix();
  5565. if (!offset) {
  5566. offset = 0;
  5567. }
  5568. Matrix.FromArrayToRef(array, offset, result);
  5569. return result;
  5570. };
  5571. /**
  5572. * Copy the content of an array into a given matrix
  5573. * @param array defines the source array
  5574. * @param offset defines an offset in the source array
  5575. * @param result defines the target matrix
  5576. */
  5577. Matrix.FromArrayToRef = function (array, offset, result) {
  5578. for (var index = 0; index < 16; index++) {
  5579. result.m[index] = array[index + offset];
  5580. }
  5581. result._markAsUpdated();
  5582. };
  5583. /**
  5584. * Stores an array into a matrix after having multiplied each component by a given factor
  5585. * @param array defines the source array
  5586. * @param offset defines the offset in the source array
  5587. * @param scale defines the scaling factor
  5588. * @param result defines the target matrix
  5589. */
  5590. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5591. for (var index = 0; index < 16; index++) {
  5592. result.m[index] = array[index + offset] * scale;
  5593. }
  5594. result._markAsUpdated();
  5595. };
  5596. /**
  5597. * Stores a list of values (16) inside a given matrix
  5598. * @param initialM11 defines 1st value of 1st row
  5599. * @param initialM12 defines 2nd value of 1st row
  5600. * @param initialM13 defines 3rd value of 1st row
  5601. * @param initialM14 defines 4th value of 1st row
  5602. * @param initialM21 defines 1st value of 2nd row
  5603. * @param initialM22 defines 2nd value of 2nd row
  5604. * @param initialM23 defines 3rd value of 2nd row
  5605. * @param initialM24 defines 4th value of 2nd row
  5606. * @param initialM31 defines 1st value of 3rd row
  5607. * @param initialM32 defines 2nd value of 3rd row
  5608. * @param initialM33 defines 3rd value of 3rd row
  5609. * @param initialM34 defines 4th value of 3rd row
  5610. * @param initialM41 defines 1st value of 4th row
  5611. * @param initialM42 defines 2nd value of 4th row
  5612. * @param initialM43 defines 3rd value of 4th row
  5613. * @param initialM44 defines 4th value of 4th row
  5614. * @param result defines the target matrix
  5615. */
  5616. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5617. result.m[0] = initialM11;
  5618. result.m[1] = initialM12;
  5619. result.m[2] = initialM13;
  5620. result.m[3] = initialM14;
  5621. result.m[4] = initialM21;
  5622. result.m[5] = initialM22;
  5623. result.m[6] = initialM23;
  5624. result.m[7] = initialM24;
  5625. result.m[8] = initialM31;
  5626. result.m[9] = initialM32;
  5627. result.m[10] = initialM33;
  5628. result.m[11] = initialM34;
  5629. result.m[12] = initialM41;
  5630. result.m[13] = initialM42;
  5631. result.m[14] = initialM43;
  5632. result.m[15] = initialM44;
  5633. result._markAsUpdated();
  5634. };
  5635. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5636. /**
  5637. * Gets an identity matrix that must not be updated
  5638. */
  5639. get: function () {
  5640. return Matrix._identityReadOnly;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. /**
  5646. * Creates new matrix from a list of values (16)
  5647. * @param initialM11 defines 1st value of 1st row
  5648. * @param initialM12 defines 2nd value of 1st row
  5649. * @param initialM13 defines 3rd value of 1st row
  5650. * @param initialM14 defines 4th value of 1st row
  5651. * @param initialM21 defines 1st value of 2nd row
  5652. * @param initialM22 defines 2nd value of 2nd row
  5653. * @param initialM23 defines 3rd value of 2nd row
  5654. * @param initialM24 defines 4th value of 2nd row
  5655. * @param initialM31 defines 1st value of 3rd row
  5656. * @param initialM32 defines 2nd value of 3rd row
  5657. * @param initialM33 defines 3rd value of 3rd row
  5658. * @param initialM34 defines 4th value of 3rd row
  5659. * @param initialM41 defines 1st value of 4th row
  5660. * @param initialM42 defines 2nd value of 4th row
  5661. * @param initialM43 defines 3rd value of 4th row
  5662. * @param initialM44 defines 4th value of 4th row
  5663. * @returns the new matrix
  5664. */
  5665. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5666. var result = new Matrix();
  5667. result.m[0] = initialM11;
  5668. result.m[1] = initialM12;
  5669. result.m[2] = initialM13;
  5670. result.m[3] = initialM14;
  5671. result.m[4] = initialM21;
  5672. result.m[5] = initialM22;
  5673. result.m[6] = initialM23;
  5674. result.m[7] = initialM24;
  5675. result.m[8] = initialM31;
  5676. result.m[9] = initialM32;
  5677. result.m[10] = initialM33;
  5678. result.m[11] = initialM34;
  5679. result.m[12] = initialM41;
  5680. result.m[13] = initialM42;
  5681. result.m[14] = initialM43;
  5682. result.m[15] = initialM44;
  5683. return result;
  5684. };
  5685. /**
  5686. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5687. * @param scale defines the scale vector3
  5688. * @param rotation defines the rotation quaternion
  5689. * @param translation defines the translation vector3
  5690. * @returns a new matrix
  5691. */
  5692. Matrix.Compose = function (scale, rotation, translation) {
  5693. var result = Matrix.Identity();
  5694. Matrix.ComposeToRef(scale, rotation, translation, result);
  5695. return result;
  5696. };
  5697. /**
  5698. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5699. * @param scale defines the scale vector3
  5700. * @param rotation defines the rotation quaternion
  5701. * @param translation defines the translation vector3
  5702. * @param result defines the target matrix
  5703. */
  5704. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5705. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5706. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5707. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5708. result.setTranslation(translation);
  5709. };
  5710. /**
  5711. * Creates a new identity matrix
  5712. * @returns a new identity matrix
  5713. */
  5714. Matrix.Identity = function () {
  5715. 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);
  5716. };
  5717. /**
  5718. * Creates a new identity matrix and stores the result in a given matrix
  5719. * @param result defines the target matrix
  5720. */
  5721. Matrix.IdentityToRef = function (result) {
  5722. 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);
  5723. };
  5724. /**
  5725. * Creates a new zero matrix
  5726. * @returns a new zero matrix
  5727. */
  5728. Matrix.Zero = function () {
  5729. 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);
  5730. };
  5731. /**
  5732. * Creates a new rotation matrix for "angle" radians around the X axis
  5733. * @param angle defines the angle (in radians) to use
  5734. * @return the new matrix
  5735. */
  5736. Matrix.RotationX = function (angle) {
  5737. var result = new Matrix();
  5738. Matrix.RotationXToRef(angle, result);
  5739. return result;
  5740. };
  5741. /**
  5742. * Creates a new matrix as the invert of a given matrix
  5743. * @param source defines the source matrix
  5744. * @returns the new matrix
  5745. */
  5746. Matrix.Invert = function (source) {
  5747. var result = new Matrix();
  5748. source.invertToRef(result);
  5749. return result;
  5750. };
  5751. /**
  5752. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5753. * @param angle defines the angle (in radians) to use
  5754. * @param result defines the target matrix
  5755. */
  5756. Matrix.RotationXToRef = function (angle, result) {
  5757. var s = Math.sin(angle);
  5758. var c = Math.cos(angle);
  5759. result.m[0] = 1.0;
  5760. result.m[15] = 1.0;
  5761. result.m[5] = c;
  5762. result.m[10] = c;
  5763. result.m[9] = -s;
  5764. result.m[6] = s;
  5765. result.m[1] = 0.0;
  5766. result.m[2] = 0.0;
  5767. result.m[3] = 0.0;
  5768. result.m[4] = 0.0;
  5769. result.m[7] = 0.0;
  5770. result.m[8] = 0.0;
  5771. result.m[11] = 0.0;
  5772. result.m[12] = 0.0;
  5773. result.m[13] = 0.0;
  5774. result.m[14] = 0.0;
  5775. result._markAsUpdated();
  5776. };
  5777. /**
  5778. * Creates a new rotation matrix for "angle" radians around the Y axis
  5779. * @param angle defines the angle (in radians) to use
  5780. * @return the new matrix
  5781. */
  5782. Matrix.RotationY = function (angle) {
  5783. var result = new Matrix();
  5784. Matrix.RotationYToRef(angle, result);
  5785. return result;
  5786. };
  5787. /**
  5788. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5789. * @param angle defines the angle (in radians) to use
  5790. * @param result defines the target matrix
  5791. */
  5792. Matrix.RotationYToRef = function (angle, result) {
  5793. var s = Math.sin(angle);
  5794. var c = Math.cos(angle);
  5795. result.m[5] = 1.0;
  5796. result.m[15] = 1.0;
  5797. result.m[0] = c;
  5798. result.m[2] = -s;
  5799. result.m[8] = s;
  5800. result.m[10] = c;
  5801. result.m[1] = 0.0;
  5802. result.m[3] = 0.0;
  5803. result.m[4] = 0.0;
  5804. result.m[6] = 0.0;
  5805. result.m[7] = 0.0;
  5806. result.m[9] = 0.0;
  5807. result.m[11] = 0.0;
  5808. result.m[12] = 0.0;
  5809. result.m[13] = 0.0;
  5810. result.m[14] = 0.0;
  5811. result._markAsUpdated();
  5812. };
  5813. /**
  5814. * Creates a new rotation matrix for "angle" radians around the Z axis
  5815. * @param angle defines the angle (in radians) to use
  5816. * @return the new matrix
  5817. */
  5818. Matrix.RotationZ = function (angle) {
  5819. var result = new Matrix();
  5820. Matrix.RotationZToRef(angle, result);
  5821. return result;
  5822. };
  5823. /**
  5824. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5825. * @param angle defines the angle (in radians) to use
  5826. * @param result defines the target matrix
  5827. */
  5828. Matrix.RotationZToRef = function (angle, result) {
  5829. var s = Math.sin(angle);
  5830. var c = Math.cos(angle);
  5831. result.m[10] = 1.0;
  5832. result.m[15] = 1.0;
  5833. result.m[0] = c;
  5834. result.m[1] = s;
  5835. result.m[4] = -s;
  5836. result.m[5] = c;
  5837. result.m[2] = 0.0;
  5838. result.m[3] = 0.0;
  5839. result.m[6] = 0.0;
  5840. result.m[7] = 0.0;
  5841. result.m[8] = 0.0;
  5842. result.m[9] = 0.0;
  5843. result.m[11] = 0.0;
  5844. result.m[12] = 0.0;
  5845. result.m[13] = 0.0;
  5846. result.m[14] = 0.0;
  5847. result._markAsUpdated();
  5848. };
  5849. /**
  5850. * Creates a new rotation matrix for "angle" radians around the given axis
  5851. * @param axis defines the axis to use
  5852. * @param angle defines the angle (in radians) to use
  5853. * @return the new matrix
  5854. */
  5855. Matrix.RotationAxis = function (axis, angle) {
  5856. var result = Matrix.Zero();
  5857. Matrix.RotationAxisToRef(axis, angle, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5862. * @param axis defines the axis to use
  5863. * @param angle defines the angle (in radians) to use
  5864. * @param result defines the target matrix
  5865. */
  5866. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5867. var s = Math.sin(-angle);
  5868. var c = Math.cos(-angle);
  5869. var c1 = 1 - c;
  5870. axis.normalize();
  5871. result.m[0] = (axis.x * axis.x) * c1 + c;
  5872. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5873. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5874. result.m[3] = 0.0;
  5875. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5876. result.m[5] = (axis.y * axis.y) * c1 + c;
  5877. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5878. result.m[7] = 0.0;
  5879. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5880. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5881. result.m[10] = (axis.z * axis.z) * c1 + c;
  5882. result.m[11] = 0.0;
  5883. result.m[15] = 1.0;
  5884. result._markAsUpdated();
  5885. };
  5886. /**
  5887. * Creates a rotation matrix
  5888. * @param yaw defines the yaw angle in radians (Y axis)
  5889. * @param pitch defines the pitch angle in radians (X axis)
  5890. * @param roll defines the roll angle in radians (X axis)
  5891. * @returns the new rotation matrix
  5892. */
  5893. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a rotation matrix and stores it in a given matrix
  5900. * @param yaw defines the yaw angle in radians (Y axis)
  5901. * @param pitch defines the pitch angle in radians (X axis)
  5902. * @param roll defines the roll angle in radians (X axis)
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5906. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5907. this._tempQuaternion.toRotationMatrix(result);
  5908. };
  5909. /**
  5910. * Creates a scaling matrix
  5911. * @param x defines the scale factor on X axis
  5912. * @param y defines the scale factor on Y axis
  5913. * @param z defines the scale factor on Z axis
  5914. * @returns the new matrix
  5915. */
  5916. Matrix.Scaling = function (x, y, z) {
  5917. var result = Matrix.Zero();
  5918. Matrix.ScalingToRef(x, y, z, result);
  5919. return result;
  5920. };
  5921. /**
  5922. * Creates a scaling matrix and stores it in a given matrix
  5923. * @param x defines the scale factor on X axis
  5924. * @param y defines the scale factor on Y axis
  5925. * @param z defines the scale factor on Z axis
  5926. * @param result defines the target matrix
  5927. */
  5928. Matrix.ScalingToRef = function (x, y, z, result) {
  5929. result.m[0] = x;
  5930. result.m[1] = 0.0;
  5931. result.m[2] = 0.0;
  5932. result.m[3] = 0.0;
  5933. result.m[4] = 0.0;
  5934. result.m[5] = y;
  5935. result.m[6] = 0.0;
  5936. result.m[7] = 0.0;
  5937. result.m[8] = 0.0;
  5938. result.m[9] = 0.0;
  5939. result.m[10] = z;
  5940. result.m[11] = 0.0;
  5941. result.m[12] = 0.0;
  5942. result.m[13] = 0.0;
  5943. result.m[14] = 0.0;
  5944. result.m[15] = 1.0;
  5945. result._markAsUpdated();
  5946. };
  5947. /**
  5948. * Creates a translation matrix
  5949. * @param x defines the translation on X axis
  5950. * @param y defines the translation on Y axis
  5951. * @param z defines the translationon Z axis
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Translation = function (x, y, z) {
  5955. var result = Matrix.Identity();
  5956. Matrix.TranslationToRef(x, y, z, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a translation matrix and stores it in a given matrix
  5961. * @param x defines the translation on X axis
  5962. * @param y defines the translation on Y axis
  5963. * @param z defines the translationon Z axis
  5964. * @param result defines the target matrix
  5965. */
  5966. Matrix.TranslationToRef = function (x, y, z, result) {
  5967. 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);
  5968. };
  5969. /**
  5970. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5971. * @param startValue defines the start value
  5972. * @param endValue defines the end value
  5973. * @param gradient defines the gradient factor
  5974. * @returns the new matrix
  5975. */
  5976. Matrix.Lerp = function (startValue, endValue, gradient) {
  5977. var result = Matrix.Zero();
  5978. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5979. return result;
  5980. };
  5981. /**
  5982. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5983. * @param startValue defines the start value
  5984. * @param endValue defines the end value
  5985. * @param gradient defines the gradient factor
  5986. * @param result defines the Matrix object where to store data
  5987. */
  5988. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5989. for (var index = 0; index < 16; index++) {
  5990. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5991. }
  5992. result._markAsUpdated();
  5993. };
  5994. /**
  5995. * Builds a new matrix whose values are computed by:
  5996. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5997. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5998. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5999. * @param startValue defines the first matrix
  6000. * @param endValue defines the second matrix
  6001. * @param gradient defines the gradient between the two matrices
  6002. * @returns the new matrix
  6003. */
  6004. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6005. var result = Matrix.Zero();
  6006. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Update a matrix to values which are computed by:
  6011. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6012. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6013. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6014. * @param startValue defines the first matrix
  6015. * @param endValue defines the second matrix
  6016. * @param gradient defines the gradient between the two matrices
  6017. * @param result defines the target matrix
  6018. */
  6019. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6020. var startScale = MathTmp.Vector3[0];
  6021. var startRotation = MathTmp.Quaternion[0];
  6022. var startTranslation = MathTmp.Vector3[1];
  6023. startValue.decompose(startScale, startRotation, startTranslation);
  6024. var endScale = MathTmp.Vector3[2];
  6025. var endRotation = MathTmp.Quaternion[1];
  6026. var endTranslation = MathTmp.Vector3[3];
  6027. endValue.decompose(endScale, endRotation, endTranslation);
  6028. var resultScale = MathTmp.Vector3[4];
  6029. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6030. var resultRotation = MathTmp.Quaternion[2];
  6031. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6032. var resultTranslation = MathTmp.Vector3[5];
  6033. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6034. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6035. };
  6036. /**
  6037. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6038. * This function works in left handed mode
  6039. * @param eye defines the final position of the entity
  6040. * @param target defines where the entity should look at
  6041. * @param up defines the up vector for the entity
  6042. * @returns the new matrix
  6043. */
  6044. Matrix.LookAtLH = function (eye, target, up) {
  6045. var result = Matrix.Zero();
  6046. Matrix.LookAtLHToRef(eye, target, up, result);
  6047. return result;
  6048. };
  6049. /**
  6050. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6051. * This function works in left handed mode
  6052. * @param eye defines the final position of the entity
  6053. * @param target defines where the entity should look at
  6054. * @param up defines the up vector for the entity
  6055. * @param result defines the target matrix
  6056. */
  6057. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6058. // Z axis
  6059. target.subtractToRef(eye, this._zAxis);
  6060. this._zAxis.normalize();
  6061. // X axis
  6062. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6063. if (this._xAxis.lengthSquared() === 0) {
  6064. this._xAxis.x = 1.0;
  6065. }
  6066. else {
  6067. this._xAxis.normalize();
  6068. }
  6069. // Y axis
  6070. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6071. this._yAxis.normalize();
  6072. // Eye angles
  6073. var ex = -Vector3.Dot(this._xAxis, eye);
  6074. var ey = -Vector3.Dot(this._yAxis, eye);
  6075. var ez = -Vector3.Dot(this._zAxis, eye);
  6076. 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);
  6077. };
  6078. /**
  6079. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6080. * This function works in right handed mode
  6081. * @param eye defines the final position of the entity
  6082. * @param target defines where the entity should look at
  6083. * @param up defines the up vector for the entity
  6084. * @returns the new matrix
  6085. */
  6086. Matrix.LookAtRH = function (eye, target, up) {
  6087. var result = Matrix.Zero();
  6088. Matrix.LookAtRHToRef(eye, target, up, result);
  6089. return result;
  6090. };
  6091. /**
  6092. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6093. * This function works in right handed mode
  6094. * @param eye defines the final position of the entity
  6095. * @param target defines where the entity should look at
  6096. * @param up defines the up vector for the entity
  6097. * @param result defines the target matrix
  6098. */
  6099. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6100. // Z axis
  6101. eye.subtractToRef(target, this._zAxis);
  6102. this._zAxis.normalize();
  6103. // X axis
  6104. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6105. if (this._xAxis.lengthSquared() === 0) {
  6106. this._xAxis.x = 1.0;
  6107. }
  6108. else {
  6109. this._xAxis.normalize();
  6110. }
  6111. // Y axis
  6112. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6113. this._yAxis.normalize();
  6114. // Eye angles
  6115. var ex = -Vector3.Dot(this._xAxis, eye);
  6116. var ey = -Vector3.Dot(this._yAxis, eye);
  6117. var ez = -Vector3.Dot(this._zAxis, eye);
  6118. 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);
  6119. };
  6120. /**
  6121. * Create a left-handed orthographic projection matrix
  6122. * @param width defines the viewport width
  6123. * @param height defines the viewport height
  6124. * @param znear defines the near clip plane
  6125. * @param zfar defines the far clip plane
  6126. * @returns a new matrix as a left-handed orthographic projection matrix
  6127. */
  6128. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6129. var matrix = Matrix.Zero();
  6130. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6131. return matrix;
  6132. };
  6133. /**
  6134. * Store a left-handed orthographic projection to a given matrix
  6135. * @param width defines the viewport width
  6136. * @param height defines the viewport height
  6137. * @param znear defines the near clip plane
  6138. * @param zfar defines the far clip plane
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6142. var n = znear;
  6143. var f = zfar;
  6144. var a = 2.0 / width;
  6145. var b = 2.0 / height;
  6146. var c = 2.0 / (f - n);
  6147. var d = -(f + n) / (f - n);
  6148. 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);
  6149. };
  6150. /**
  6151. * Create a left-handed orthographic projection matrix
  6152. * @param left defines the viewport left coordinate
  6153. * @param right defines the viewport right coordinate
  6154. * @param bottom defines the viewport bottom coordinate
  6155. * @param top defines the viewport top coordinate
  6156. * @param znear defines the near clip plane
  6157. * @param zfar defines the far clip plane
  6158. * @returns a new matrix as a left-handed orthographic projection matrix
  6159. */
  6160. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6161. var matrix = Matrix.Zero();
  6162. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6163. return matrix;
  6164. };
  6165. /**
  6166. * Stores a left-handed orthographic projection into a given matrix
  6167. * @param left defines the viewport left coordinate
  6168. * @param right defines the viewport right coordinate
  6169. * @param bottom defines the viewport bottom coordinate
  6170. * @param top defines the viewport top coordinate
  6171. * @param znear defines the near clip plane
  6172. * @param zfar defines the far clip plane
  6173. * @param result defines the target matrix
  6174. */
  6175. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6176. var n = znear;
  6177. var f = zfar;
  6178. var a = 2.0 / (right - left);
  6179. var b = 2.0 / (top - bottom);
  6180. var c = 2.0 / (f - n);
  6181. var d = -(f + n) / (f - n);
  6182. var i0 = (left + right) / (left - right);
  6183. var i1 = (top + bottom) / (bottom - top);
  6184. 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);
  6185. };
  6186. /**
  6187. * Creates a right-handed orthographic projection matrix
  6188. * @param left defines the viewport left coordinate
  6189. * @param right defines the viewport right coordinate
  6190. * @param bottom defines the viewport bottom coordinate
  6191. * @param top defines the viewport top coordinate
  6192. * @param znear defines the near clip plane
  6193. * @param zfar defines the far clip plane
  6194. * @returns a new matrix as a right-handed orthographic projection matrix
  6195. */
  6196. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6197. var matrix = Matrix.Zero();
  6198. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6199. return matrix;
  6200. };
  6201. /**
  6202. * Stores a right-handed orthographic projection into a given matrix
  6203. * @param left defines the viewport left coordinate
  6204. * @param right defines the viewport right coordinate
  6205. * @param bottom defines the viewport bottom coordinate
  6206. * @param top defines the viewport top coordinate
  6207. * @param znear defines the near clip plane
  6208. * @param zfar defines the far clip plane
  6209. * @param result defines the target matrix
  6210. */
  6211. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6212. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6213. result.m[10] *= -1.0;
  6214. };
  6215. /**
  6216. * Creates a left-handed perspective projection matrix
  6217. * @param width defines the viewport width
  6218. * @param height defines the viewport height
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a left-handed perspective projection matrix
  6222. */
  6223. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. var n = znear;
  6226. var f = zfar;
  6227. var a = 2.0 * n / width;
  6228. var b = 2.0 * n / height;
  6229. var c = (f + n) / (f - n);
  6230. var d = -2.0 * f * n / (f - n);
  6231. 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);
  6232. return matrix;
  6233. };
  6234. /**
  6235. * Creates a left-handed perspective projection matrix
  6236. * @param fov defines the horizontal field of view
  6237. * @param aspect defines the aspect ratio
  6238. * @param znear defines the near clip plane
  6239. * @param zfar defines the far clip plane
  6240. * @returns a new matrix as a left-handed perspective projection matrix
  6241. */
  6242. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6243. var matrix = Matrix.Zero();
  6244. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6245. return matrix;
  6246. };
  6247. /**
  6248. * Stores a left-handed perspective projection into a given matrix
  6249. * @param fov defines the horizontal field of view
  6250. * @param aspect defines the aspect ratio
  6251. * @param znear defines the near clip plane
  6252. * @param zfar defines the far clip plane
  6253. * @param result defines the target matrix
  6254. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6255. */
  6256. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6257. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6258. var n = znear;
  6259. var f = zfar;
  6260. var t = 1.0 / (Math.tan(fov * 0.5));
  6261. var a = isVerticalFovFixed ? (t / aspect) : t;
  6262. var b = isVerticalFovFixed ? t : (t * aspect);
  6263. var c = (f + n) / (f - n);
  6264. var d = -2.0 * f * n / (f - n);
  6265. 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);
  6266. };
  6267. /**
  6268. * Creates a right-handed perspective projection matrix
  6269. * @param fov defines the horizontal field of view
  6270. * @param aspect defines the aspect ratio
  6271. * @param znear defines the near clip plane
  6272. * @param zfar defines the far clip plane
  6273. * @returns a new matrix as a right-handed perspective projection matrix
  6274. */
  6275. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6276. var matrix = Matrix.Zero();
  6277. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6278. return matrix;
  6279. };
  6280. /**
  6281. * Stores a right-handed perspective projection into a given matrix
  6282. * @param fov defines the horizontal field of view
  6283. * @param aspect defines the aspect ratio
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6288. */
  6289. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6290. //alternatively this could be expressed as:
  6291. // m = PerspectiveFovLHToRef
  6292. // m[10] *= -1.0;
  6293. // m[11] *= -1.0;
  6294. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6295. var n = znear;
  6296. var f = zfar;
  6297. var t = 1.0 / (Math.tan(fov * 0.5));
  6298. var a = isVerticalFovFixed ? (t / aspect) : t;
  6299. var b = isVerticalFovFixed ? t : (t * aspect);
  6300. var c = -(f + n) / (f - n);
  6301. var d = -2 * f * n / (f - n);
  6302. 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);
  6303. };
  6304. /**
  6305. * Stores a perspective projection for WebVR info a given matrix
  6306. * @param fov defines the field of view
  6307. * @param znear defines the near clip plane
  6308. * @param zfar defines the far clip plane
  6309. * @param result defines the target matrix
  6310. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6311. */
  6312. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6313. if (rightHanded === void 0) { rightHanded = false; }
  6314. var rightHandedFactor = rightHanded ? -1 : 1;
  6315. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6316. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6317. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6318. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6319. var xScale = 2.0 / (leftTan + rightTan);
  6320. var yScale = 2.0 / (upTan + downTan);
  6321. result.m[0] = xScale;
  6322. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6323. result.m[5] = yScale;
  6324. result.m[6] = result.m[7] = 0.0;
  6325. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6326. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6327. result.m[10] = -zfar / (znear - zfar);
  6328. result.m[11] = 1.0 * rightHandedFactor;
  6329. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6330. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6331. result._markAsUpdated();
  6332. };
  6333. /**
  6334. * Computes a complete transformation matrix
  6335. * @param viewport defines the viewport to use
  6336. * @param world defines the world matrix
  6337. * @param view defines the view matrix
  6338. * @param projection defines the projection matrix
  6339. * @param zmin defines the near clip plane
  6340. * @param zmax defines the far clip plane
  6341. * @returns the transformation matrix
  6342. */
  6343. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6344. var cw = viewport.width;
  6345. var ch = viewport.height;
  6346. var cx = viewport.x;
  6347. var cy = viewport.y;
  6348. 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);
  6349. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6350. };
  6351. /**
  6352. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6353. * @param matrix defines the matrix to use
  6354. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6355. */
  6356. Matrix.GetAsMatrix2x2 = function (matrix) {
  6357. return new Float32Array([
  6358. matrix.m[0], matrix.m[1],
  6359. matrix.m[4], matrix.m[5]
  6360. ]);
  6361. };
  6362. /**
  6363. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6364. * @param matrix defines the matrix to use
  6365. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6366. */
  6367. Matrix.GetAsMatrix3x3 = function (matrix) {
  6368. return new Float32Array([
  6369. matrix.m[0], matrix.m[1], matrix.m[2],
  6370. matrix.m[4], matrix.m[5], matrix.m[6],
  6371. matrix.m[8], matrix.m[9], matrix.m[10]
  6372. ]);
  6373. };
  6374. /**
  6375. * Compute the transpose of a given matrix
  6376. * @param matrix defines the matrix to transpose
  6377. * @returns the new matrix
  6378. */
  6379. Matrix.Transpose = function (matrix) {
  6380. var result = new Matrix();
  6381. Matrix.TransposeToRef(matrix, result);
  6382. return result;
  6383. };
  6384. /**
  6385. * Compute the transpose of a matrix and store it in a target matrix
  6386. * @param matrix defines the matrix to transpose
  6387. * @param result defines the target matrix
  6388. */
  6389. Matrix.TransposeToRef = function (matrix, result) {
  6390. result.m[0] = matrix.m[0];
  6391. result.m[1] = matrix.m[4];
  6392. result.m[2] = matrix.m[8];
  6393. result.m[3] = matrix.m[12];
  6394. result.m[4] = matrix.m[1];
  6395. result.m[5] = matrix.m[5];
  6396. result.m[6] = matrix.m[9];
  6397. result.m[7] = matrix.m[13];
  6398. result.m[8] = matrix.m[2];
  6399. result.m[9] = matrix.m[6];
  6400. result.m[10] = matrix.m[10];
  6401. result.m[11] = matrix.m[14];
  6402. result.m[12] = matrix.m[3];
  6403. result.m[13] = matrix.m[7];
  6404. result.m[14] = matrix.m[11];
  6405. result.m[15] = matrix.m[15];
  6406. };
  6407. /**
  6408. * Computes a reflection matrix from a plane
  6409. * @param plane defines the reflection plane
  6410. * @returns a new matrix
  6411. */
  6412. Matrix.Reflection = function (plane) {
  6413. var matrix = new Matrix();
  6414. Matrix.ReflectionToRef(plane, matrix);
  6415. return matrix;
  6416. };
  6417. /**
  6418. * Computes a reflection matrix from a plane
  6419. * @param plane defines the reflection plane
  6420. * @param result defines the target matrix
  6421. */
  6422. Matrix.ReflectionToRef = function (plane, result) {
  6423. plane.normalize();
  6424. var x = plane.normal.x;
  6425. var y = plane.normal.y;
  6426. var z = plane.normal.z;
  6427. var temp = -2 * x;
  6428. var temp2 = -2 * y;
  6429. var temp3 = -2 * z;
  6430. result.m[0] = (temp * x) + 1;
  6431. result.m[1] = temp2 * x;
  6432. result.m[2] = temp3 * x;
  6433. result.m[3] = 0.0;
  6434. result.m[4] = temp * y;
  6435. result.m[5] = (temp2 * y) + 1;
  6436. result.m[6] = temp3 * y;
  6437. result.m[7] = 0.0;
  6438. result.m[8] = temp * z;
  6439. result.m[9] = temp2 * z;
  6440. result.m[10] = (temp3 * z) + 1;
  6441. result.m[11] = 0.0;
  6442. result.m[12] = temp * plane.d;
  6443. result.m[13] = temp2 * plane.d;
  6444. result.m[14] = temp3 * plane.d;
  6445. result.m[15] = 1.0;
  6446. result._markAsUpdated();
  6447. };
  6448. /**
  6449. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6450. * @param xaxis defines the value of the 1st axis
  6451. * @param yaxis defines the value of the 2nd axis
  6452. * @param zaxis defines the value of the 3rd axis
  6453. * @param result defines the target matrix
  6454. */
  6455. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6456. result.m[0] = xaxis.x;
  6457. result.m[1] = xaxis.y;
  6458. result.m[2] = xaxis.z;
  6459. result.m[3] = 0.0;
  6460. result.m[4] = yaxis.x;
  6461. result.m[5] = yaxis.y;
  6462. result.m[6] = yaxis.z;
  6463. result.m[7] = 0.0;
  6464. result.m[8] = zaxis.x;
  6465. result.m[9] = zaxis.y;
  6466. result.m[10] = zaxis.z;
  6467. result.m[11] = 0.0;
  6468. result.m[12] = 0.0;
  6469. result.m[13] = 0.0;
  6470. result.m[14] = 0.0;
  6471. result.m[15] = 1.0;
  6472. result._markAsUpdated();
  6473. };
  6474. /**
  6475. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6476. * @param quat defines the quaternion to use
  6477. * @param result defines the target matrix
  6478. */
  6479. Matrix.FromQuaternionToRef = function (quat, result) {
  6480. var xx = quat.x * quat.x;
  6481. var yy = quat.y * quat.y;
  6482. var zz = quat.z * quat.z;
  6483. var xy = quat.x * quat.y;
  6484. var zw = quat.z * quat.w;
  6485. var zx = quat.z * quat.x;
  6486. var yw = quat.y * quat.w;
  6487. var yz = quat.y * quat.z;
  6488. var xw = quat.x * quat.w;
  6489. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6490. result.m[1] = 2.0 * (xy + zw);
  6491. result.m[2] = 2.0 * (zx - yw);
  6492. result.m[3] = 0.0;
  6493. result.m[4] = 2.0 * (xy - zw);
  6494. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6495. result.m[6] = 2.0 * (yz + xw);
  6496. result.m[7] = 0.0;
  6497. result.m[8] = 2.0 * (zx + yw);
  6498. result.m[9] = 2.0 * (yz - xw);
  6499. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6500. result.m[11] = 0.0;
  6501. result.m[12] = 0.0;
  6502. result.m[13] = 0.0;
  6503. result.m[14] = 0.0;
  6504. result.m[15] = 1.0;
  6505. result._markAsUpdated();
  6506. };
  6507. Matrix._tempQuaternion = new Quaternion();
  6508. Matrix._xAxis = Vector3.Zero();
  6509. Matrix._yAxis = Vector3.Zero();
  6510. Matrix._zAxis = Vector3.Zero();
  6511. Matrix._updateFlagSeed = 0;
  6512. Matrix._identityReadOnly = Matrix.Identity();
  6513. return Matrix;
  6514. }());
  6515. BABYLON.Matrix = Matrix;
  6516. var Plane = /** @class */ (function () {
  6517. /**
  6518. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6519. */
  6520. function Plane(a, b, c, d) {
  6521. this.normal = new Vector3(a, b, c);
  6522. this.d = d;
  6523. }
  6524. /**
  6525. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6526. */
  6527. Plane.prototype.asArray = function () {
  6528. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6529. };
  6530. // Methods
  6531. /**
  6532. * Returns a new plane copied from the current Plane.
  6533. */
  6534. Plane.prototype.clone = function () {
  6535. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6536. };
  6537. /**
  6538. * Returns the string "Plane".
  6539. */
  6540. Plane.prototype.getClassName = function () {
  6541. return "Plane";
  6542. };
  6543. /**
  6544. * Returns the Plane hash code.
  6545. */
  6546. Plane.prototype.getHashCode = function () {
  6547. var hash = this.normal.getHashCode();
  6548. hash = (hash * 397) ^ (this.d || 0);
  6549. return hash;
  6550. };
  6551. /**
  6552. * Normalize the current Plane in place.
  6553. * Returns the updated Plane.
  6554. */
  6555. Plane.prototype.normalize = function () {
  6556. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6557. var magnitude = 0.0;
  6558. if (norm !== 0) {
  6559. magnitude = 1.0 / norm;
  6560. }
  6561. this.normal.x *= magnitude;
  6562. this.normal.y *= magnitude;
  6563. this.normal.z *= magnitude;
  6564. this.d *= magnitude;
  6565. return this;
  6566. };
  6567. /**
  6568. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6569. */
  6570. Plane.prototype.transform = function (transformation) {
  6571. var transposedMatrix = Matrix.Transpose(transformation);
  6572. var x = this.normal.x;
  6573. var y = this.normal.y;
  6574. var z = this.normal.z;
  6575. var d = this.d;
  6576. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6577. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6578. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6579. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6580. return new Plane(normalX, normalY, normalZ, finalD);
  6581. };
  6582. /**
  6583. * Returns the dot product (float) of the point coordinates and the plane normal.
  6584. */
  6585. Plane.prototype.dotCoordinate = function (point) {
  6586. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6587. };
  6588. /**
  6589. * Updates the current Plane from the plane defined by the three given points.
  6590. * Returns the updated Plane.
  6591. */
  6592. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6593. var x1 = point2.x - point1.x;
  6594. var y1 = point2.y - point1.y;
  6595. var z1 = point2.z - point1.z;
  6596. var x2 = point3.x - point1.x;
  6597. var y2 = point3.y - point1.y;
  6598. var z2 = point3.z - point1.z;
  6599. var yz = (y1 * z2) - (z1 * y2);
  6600. var xz = (z1 * x2) - (x1 * z2);
  6601. var xy = (x1 * y2) - (y1 * x2);
  6602. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6603. var invPyth;
  6604. if (pyth !== 0) {
  6605. invPyth = 1.0 / pyth;
  6606. }
  6607. else {
  6608. invPyth = 0.0;
  6609. }
  6610. this.normal.x = yz * invPyth;
  6611. this.normal.y = xz * invPyth;
  6612. this.normal.z = xy * invPyth;
  6613. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6614. return this;
  6615. };
  6616. /**
  6617. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6618. */
  6619. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6620. var dot = Vector3.Dot(this.normal, direction);
  6621. return (dot <= epsilon);
  6622. };
  6623. /**
  6624. * Returns the signed distance (float) from the given point to the Plane.
  6625. */
  6626. Plane.prototype.signedDistanceTo = function (point) {
  6627. return Vector3.Dot(point, this.normal) + this.d;
  6628. };
  6629. // Statics
  6630. /**
  6631. * Returns a new Plane from the given array.
  6632. */
  6633. Plane.FromArray = function (array) {
  6634. return new Plane(array[0], array[1], array[2], array[3]);
  6635. };
  6636. /**
  6637. * Returns a new Plane defined by the three given points.
  6638. */
  6639. Plane.FromPoints = function (point1, point2, point3) {
  6640. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6641. result.copyFromPoints(point1, point2, point3);
  6642. return result;
  6643. };
  6644. /**
  6645. * Returns a new Plane the normal vector to this plane at the given origin point.
  6646. * Note : the vector "normal" is updated because normalized.
  6647. */
  6648. Plane.FromPositionAndNormal = function (origin, normal) {
  6649. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6650. normal.normalize();
  6651. result.normal = normal;
  6652. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6653. return result;
  6654. };
  6655. /**
  6656. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6657. */
  6658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6660. return Vector3.Dot(point, normal) + d;
  6661. };
  6662. return Plane;
  6663. }());
  6664. BABYLON.Plane = Plane;
  6665. var Viewport = /** @class */ (function () {
  6666. /**
  6667. * Creates a Viewport object located at (x, y) and sized (width, height).
  6668. */
  6669. function Viewport(x, y, width, height) {
  6670. this.x = x;
  6671. this.y = y;
  6672. this.width = width;
  6673. this.height = height;
  6674. }
  6675. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6676. if (renderWidthOrEngine.getRenderWidth) {
  6677. var engine = renderWidthOrEngine;
  6678. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6679. }
  6680. var renderWidth = renderWidthOrEngine;
  6681. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6682. };
  6683. /**
  6684. * Returns a new Viewport copied from the current one.
  6685. */
  6686. Viewport.prototype.clone = function () {
  6687. return new Viewport(this.x, this.y, this.width, this.height);
  6688. };
  6689. return Viewport;
  6690. }());
  6691. BABYLON.Viewport = Viewport;
  6692. var Frustum = /** @class */ (function () {
  6693. function Frustum() {
  6694. }
  6695. /**
  6696. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6697. */
  6698. Frustum.GetPlanes = function (transform) {
  6699. var frustumPlanes = [];
  6700. for (var index = 0; index < 6; index++) {
  6701. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6702. }
  6703. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6704. return frustumPlanes;
  6705. };
  6706. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6707. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6708. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6709. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6710. frustumPlane.d = transform.m[15] + transform.m[14];
  6711. frustumPlane.normalize();
  6712. };
  6713. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6714. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6715. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6716. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6717. frustumPlane.d = transform.m[15] - transform.m[14];
  6718. frustumPlane.normalize();
  6719. };
  6720. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6721. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6722. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6723. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6724. frustumPlane.d = transform.m[15] + transform.m[12];
  6725. frustumPlane.normalize();
  6726. };
  6727. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6728. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6729. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6730. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6731. frustumPlane.d = transform.m[15] - transform.m[12];
  6732. frustumPlane.normalize();
  6733. };
  6734. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6735. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6736. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6737. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6738. frustumPlane.d = transform.m[15] - transform.m[13];
  6739. frustumPlane.normalize();
  6740. };
  6741. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6742. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6743. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6744. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6745. frustumPlane.d = transform.m[15] + transform.m[13];
  6746. frustumPlane.normalize();
  6747. };
  6748. /**
  6749. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6750. */
  6751. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6752. // Near
  6753. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6754. // Far
  6755. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6756. // Left
  6757. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6758. // Right
  6759. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6760. // Top
  6761. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6762. // Bottom
  6763. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6764. };
  6765. return Frustum;
  6766. }());
  6767. BABYLON.Frustum = Frustum;
  6768. /** Defines supported spaces */
  6769. var Space;
  6770. (function (Space) {
  6771. /** Local (object) space */
  6772. Space[Space["LOCAL"] = 0] = "LOCAL";
  6773. /** World space */
  6774. Space[Space["WORLD"] = 1] = "WORLD";
  6775. /** Bone space */
  6776. Space[Space["BONE"] = 2] = "BONE";
  6777. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6778. /** Defines the 3 main axes */
  6779. var Axis = /** @class */ (function () {
  6780. function Axis() {
  6781. }
  6782. /** X axis */
  6783. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6784. /** Y axis */
  6785. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6786. /** Z axis */
  6787. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6788. return Axis;
  6789. }());
  6790. BABYLON.Axis = Axis;
  6791. ;
  6792. var BezierCurve = /** @class */ (function () {
  6793. function BezierCurve() {
  6794. }
  6795. /**
  6796. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6797. */
  6798. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6799. // Extract X (which is equal to time here)
  6800. var f0 = 1 - 3 * x2 + 3 * x1;
  6801. var f1 = 3 * x2 - 6 * x1;
  6802. var f2 = 3 * x1;
  6803. var refinedT = t;
  6804. for (var i = 0; i < 5; i++) {
  6805. var refinedT2 = refinedT * refinedT;
  6806. var refinedT3 = refinedT2 * refinedT;
  6807. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6808. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6809. refinedT -= (x - t) * slope;
  6810. refinedT = Math.min(1, Math.max(0, refinedT));
  6811. }
  6812. // Resolve cubic bezier for the given x
  6813. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6814. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6815. Math.pow(refinedT, 3);
  6816. };
  6817. return BezierCurve;
  6818. }());
  6819. BABYLON.BezierCurve = BezierCurve;
  6820. /**
  6821. * Defines potential orientation for back face culling
  6822. */
  6823. var Orientation;
  6824. (function (Orientation) {
  6825. /**
  6826. * Clockwise
  6827. */
  6828. Orientation[Orientation["CW"] = 0] = "CW";
  6829. /** Counter clockwise */
  6830. Orientation[Orientation["CCW"] = 1] = "CCW";
  6831. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6832. /**
  6833. * Defines angle representation
  6834. */
  6835. var Angle = /** @class */ (function () {
  6836. /**
  6837. * Creates an Angle object of "radians" radians (float).
  6838. */
  6839. function Angle(radians) {
  6840. this._radians = radians;
  6841. if (this._radians < 0.0)
  6842. this._radians += (2.0 * Math.PI);
  6843. }
  6844. /**
  6845. * Get value in degrees
  6846. * @returns the Angle value in degrees (float)
  6847. */
  6848. Angle.prototype.degrees = function () {
  6849. return this._radians * 180.0 / Math.PI;
  6850. };
  6851. /**
  6852. * Get value in radians
  6853. * @returns the Angle value in radians (float)
  6854. */
  6855. Angle.prototype.radians = function () {
  6856. return this._radians;
  6857. };
  6858. /**
  6859. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6860. * @param a defines first vector
  6861. * @param b defines second vector
  6862. * @returns a new Angle
  6863. */
  6864. Angle.BetweenTwoPoints = function (a, b) {
  6865. var delta = b.subtract(a);
  6866. var theta = Math.atan2(delta.y, delta.x);
  6867. return new Angle(theta);
  6868. };
  6869. /**
  6870. * Gets a new Angle object from the given float in radians
  6871. * @param radians defines the angle value in radians
  6872. * @returns a new Angle
  6873. */
  6874. Angle.FromRadians = function (radians) {
  6875. return new Angle(radians);
  6876. };
  6877. /**
  6878. * Gets a new Angle object from the given float in degrees
  6879. * @param degrees defines the angle value in degrees
  6880. * @returns a new Angle
  6881. */
  6882. Angle.FromDegrees = function (degrees) {
  6883. return new Angle(degrees * Math.PI / 180.0);
  6884. };
  6885. return Angle;
  6886. }());
  6887. BABYLON.Angle = Angle;
  6888. var Arc2 = /** @class */ (function () {
  6889. /**
  6890. * Creates an Arc object from the three given points : start, middle and end.
  6891. */
  6892. function Arc2(startPoint, midPoint, endPoint) {
  6893. this.startPoint = startPoint;
  6894. this.midPoint = midPoint;
  6895. this.endPoint = endPoint;
  6896. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6897. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6898. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6899. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6900. 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);
  6901. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6902. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6903. var a1 = this.startAngle.degrees();
  6904. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6905. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6906. // angles correction
  6907. if (a2 - a1 > +180.0)
  6908. a2 -= 360.0;
  6909. if (a2 - a1 < -180.0)
  6910. a2 += 360.0;
  6911. if (a3 - a2 > +180.0)
  6912. a3 -= 360.0;
  6913. if (a3 - a2 < -180.0)
  6914. a3 += 360.0;
  6915. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6916. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6917. }
  6918. return Arc2;
  6919. }());
  6920. BABYLON.Arc2 = Arc2;
  6921. var Path2 = /** @class */ (function () {
  6922. /**
  6923. * Creates a Path2 object from the starting 2D coordinates x and y.
  6924. */
  6925. function Path2(x, y) {
  6926. this._points = new Array();
  6927. this._length = 0.0;
  6928. this.closed = false;
  6929. this._points.push(new Vector2(x, y));
  6930. }
  6931. /**
  6932. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6933. * Returns the updated Path2.
  6934. */
  6935. Path2.prototype.addLineTo = function (x, y) {
  6936. if (this.closed) {
  6937. return this;
  6938. }
  6939. var newPoint = new Vector2(x, y);
  6940. var previousPoint = this._points[this._points.length - 1];
  6941. this._points.push(newPoint);
  6942. this._length += newPoint.subtract(previousPoint).length();
  6943. return this;
  6944. };
  6945. /**
  6946. * 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.
  6947. * Returns the updated Path2.
  6948. */
  6949. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6950. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6951. if (this.closed) {
  6952. return this;
  6953. }
  6954. var startPoint = this._points[this._points.length - 1];
  6955. var midPoint = new Vector2(midX, midY);
  6956. var endPoint = new Vector2(endX, endY);
  6957. var arc = new Arc2(startPoint, midPoint, endPoint);
  6958. var increment = arc.angle.radians() / numberOfSegments;
  6959. if (arc.orientation === Orientation.CW)
  6960. increment *= -1;
  6961. var currentAngle = arc.startAngle.radians() + increment;
  6962. for (var i = 0; i < numberOfSegments; i++) {
  6963. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6964. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6965. this.addLineTo(x, y);
  6966. currentAngle += increment;
  6967. }
  6968. return this;
  6969. };
  6970. /**
  6971. * Closes the Path2.
  6972. * Returns the Path2.
  6973. */
  6974. Path2.prototype.close = function () {
  6975. this.closed = true;
  6976. return this;
  6977. };
  6978. /**
  6979. * Returns the Path2 total length (float).
  6980. */
  6981. Path2.prototype.length = function () {
  6982. var result = this._length;
  6983. if (!this.closed) {
  6984. var lastPoint = this._points[this._points.length - 1];
  6985. var firstPoint = this._points[0];
  6986. result += (firstPoint.subtract(lastPoint).length());
  6987. }
  6988. return result;
  6989. };
  6990. /**
  6991. * Returns the Path2 internal array of points.
  6992. */
  6993. Path2.prototype.getPoints = function () {
  6994. return this._points;
  6995. };
  6996. /**
  6997. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6998. */
  6999. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7000. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7001. return Vector2.Zero();
  7002. }
  7003. var lengthPosition = normalizedLengthPosition * this.length();
  7004. var previousOffset = 0;
  7005. for (var i = 0; i < this._points.length; i++) {
  7006. var j = (i + 1) % this._points.length;
  7007. var a = this._points[i];
  7008. var b = this._points[j];
  7009. var bToA = b.subtract(a);
  7010. var nextOffset = (bToA.length() + previousOffset);
  7011. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7012. var dir = bToA.normalize();
  7013. var localOffset = lengthPosition - previousOffset;
  7014. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7015. }
  7016. previousOffset = nextOffset;
  7017. }
  7018. return Vector2.Zero();
  7019. };
  7020. /**
  7021. * Returns a new Path2 starting at the coordinates (x, y).
  7022. */
  7023. Path2.StartingAt = function (x, y) {
  7024. return new Path2(x, y);
  7025. };
  7026. return Path2;
  7027. }());
  7028. BABYLON.Path2 = Path2;
  7029. var Path3D = /** @class */ (function () {
  7030. /**
  7031. * new Path3D(path, normal, raw)
  7032. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7033. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7034. * path : an array of Vector3, the curve axis of the Path3D
  7035. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7036. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7037. */
  7038. function Path3D(path, firstNormal, raw) {
  7039. if (firstNormal === void 0) { firstNormal = null; }
  7040. this.path = path;
  7041. this._curve = new Array();
  7042. this._distances = new Array();
  7043. this._tangents = new Array();
  7044. this._normals = new Array();
  7045. this._binormals = new Array();
  7046. for (var p = 0; p < path.length; p++) {
  7047. this._curve[p] = path[p].clone(); // hard copy
  7048. }
  7049. this._raw = raw || false;
  7050. this._compute(firstNormal);
  7051. }
  7052. /**
  7053. * Returns the Path3D array of successive Vector3 designing its curve.
  7054. */
  7055. Path3D.prototype.getCurve = function () {
  7056. return this._curve;
  7057. };
  7058. /**
  7059. * Returns an array populated with tangent vectors on each Path3D curve point.
  7060. */
  7061. Path3D.prototype.getTangents = function () {
  7062. return this._tangents;
  7063. };
  7064. /**
  7065. * Returns an array populated with normal vectors on each Path3D curve point.
  7066. */
  7067. Path3D.prototype.getNormals = function () {
  7068. return this._normals;
  7069. };
  7070. /**
  7071. * Returns an array populated with binormal vectors on each Path3D curve point.
  7072. */
  7073. Path3D.prototype.getBinormals = function () {
  7074. return this._binormals;
  7075. };
  7076. /**
  7077. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7078. */
  7079. Path3D.prototype.getDistances = function () {
  7080. return this._distances;
  7081. };
  7082. /**
  7083. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7084. * Returns the same object updated.
  7085. */
  7086. Path3D.prototype.update = function (path, firstNormal) {
  7087. if (firstNormal === void 0) { firstNormal = null; }
  7088. for (var p = 0; p < path.length; p++) {
  7089. this._curve[p].x = path[p].x;
  7090. this._curve[p].y = path[p].y;
  7091. this._curve[p].z = path[p].z;
  7092. }
  7093. this._compute(firstNormal);
  7094. return this;
  7095. };
  7096. // private function compute() : computes tangents, normals and binormals
  7097. Path3D.prototype._compute = function (firstNormal) {
  7098. var l = this._curve.length;
  7099. // first and last tangents
  7100. this._tangents[0] = this._getFirstNonNullVector(0);
  7101. if (!this._raw) {
  7102. this._tangents[0].normalize();
  7103. }
  7104. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7105. if (!this._raw) {
  7106. this._tangents[l - 1].normalize();
  7107. }
  7108. // normals and binormals at first point : arbitrary vector with _normalVector()
  7109. var tg0 = this._tangents[0];
  7110. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7111. this._normals[0] = pp0;
  7112. if (!this._raw) {
  7113. this._normals[0].normalize();
  7114. }
  7115. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7116. if (!this._raw) {
  7117. this._binormals[0].normalize();
  7118. }
  7119. this._distances[0] = 0.0;
  7120. // normals and binormals : next points
  7121. var prev; // previous vector (segment)
  7122. var cur; // current vector (segment)
  7123. var curTang; // current tangent
  7124. // previous normal
  7125. var prevBinor; // previous binormal
  7126. for (var i = 1; i < l; i++) {
  7127. // tangents
  7128. prev = this._getLastNonNullVector(i);
  7129. if (i < l - 1) {
  7130. cur = this._getFirstNonNullVector(i);
  7131. this._tangents[i] = prev.add(cur);
  7132. this._tangents[i].normalize();
  7133. }
  7134. this._distances[i] = this._distances[i - 1] + prev.length();
  7135. // normals and binormals
  7136. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7137. curTang = this._tangents[i];
  7138. prevBinor = this._binormals[i - 1];
  7139. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7140. if (!this._raw) {
  7141. this._normals[i].normalize();
  7142. }
  7143. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7144. if (!this._raw) {
  7145. this._binormals[i].normalize();
  7146. }
  7147. }
  7148. };
  7149. // private function getFirstNonNullVector(index)
  7150. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7151. Path3D.prototype._getFirstNonNullVector = function (index) {
  7152. var i = 1;
  7153. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7154. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7155. i++;
  7156. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7157. }
  7158. return nNVector;
  7159. };
  7160. // private function getLastNonNullVector(index)
  7161. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7162. Path3D.prototype._getLastNonNullVector = function (index) {
  7163. var i = 1;
  7164. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7165. while (nLVector.length() === 0 && index > i + 1) {
  7166. i++;
  7167. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7168. }
  7169. return nLVector;
  7170. };
  7171. // private function normalVector(v0, vt, va) :
  7172. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7173. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7174. Path3D.prototype._normalVector = function (v0, vt, va) {
  7175. var normal0;
  7176. var tgl = vt.length();
  7177. if (tgl === 0.0) {
  7178. tgl = 1.0;
  7179. }
  7180. if (va === undefined || va === null) {
  7181. var point;
  7182. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7183. point = new Vector3(0.0, -1.0, 0.0);
  7184. }
  7185. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7186. point = new Vector3(1.0, 0.0, 0.0);
  7187. }
  7188. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7189. point = new Vector3(0.0, 0.0, 1.0);
  7190. }
  7191. else {
  7192. point = Vector3.Zero();
  7193. }
  7194. normal0 = Vector3.Cross(vt, point);
  7195. }
  7196. else {
  7197. normal0 = Vector3.Cross(vt, va);
  7198. Vector3.CrossToRef(normal0, vt, normal0);
  7199. }
  7200. normal0.normalize();
  7201. return normal0;
  7202. };
  7203. return Path3D;
  7204. }());
  7205. BABYLON.Path3D = Path3D;
  7206. var Curve3 = /** @class */ (function () {
  7207. /**
  7208. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7209. * A Curve3 is designed from a series of successive Vector3.
  7210. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7211. */
  7212. function Curve3(points) {
  7213. this._length = 0.0;
  7214. this._points = points;
  7215. this._length = this._computeLength(points);
  7216. }
  7217. /**
  7218. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7219. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7220. * @param v1 (Vector3) the control point
  7221. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7222. * @param nbPoints (integer) the wanted number of points in the curve
  7223. */
  7224. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7225. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7226. var bez = new Array();
  7227. var equation = function (t, val0, val1, val2) {
  7228. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7229. return res;
  7230. };
  7231. for (var i = 0; i <= nbPoints; i++) {
  7232. 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)));
  7233. }
  7234. return new Curve3(bez);
  7235. };
  7236. /**
  7237. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7238. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7239. * @param v1 (Vector3) the first control point
  7240. * @param v2 (Vector3) the second control point
  7241. * @param v3 (Vector3) the end point of the Cubic Bezier
  7242. * @param nbPoints (integer) the wanted number of points in the curve
  7243. */
  7244. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7245. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7246. var bez = new Array();
  7247. var equation = function (t, val0, val1, val2, val3) {
  7248. 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;
  7249. return res;
  7250. };
  7251. for (var i = 0; i <= nbPoints; i++) {
  7252. 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)));
  7253. }
  7254. return new Curve3(bez);
  7255. };
  7256. /**
  7257. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7258. * @param p1 (Vector3) the origin point of the Hermite Spline
  7259. * @param t1 (Vector3) the tangent vector at the origin point
  7260. * @param p2 (Vector3) the end point of the Hermite Spline
  7261. * @param t2 (Vector3) the tangent vector at the end point
  7262. * @param nbPoints (integer) the wanted number of points in the curve
  7263. */
  7264. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7265. var hermite = new Array();
  7266. var step = 1.0 / nbPoints;
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7269. }
  7270. return new Curve3(hermite);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a CatmullRom Spline curve :
  7274. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7275. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7276. */
  7277. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7278. var totalPoints = new Array();
  7279. totalPoints.push(points[0].clone());
  7280. Array.prototype.push.apply(totalPoints, points);
  7281. totalPoints.push(points[points.length - 1].clone());
  7282. var catmullRom = new Array();
  7283. var step = 1.0 / nbPoints;
  7284. var amount = 0.0;
  7285. for (var i = 0; i < totalPoints.length - 3; i++) {
  7286. amount = 0;
  7287. for (var c = 0; c < nbPoints; c++) {
  7288. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7289. amount += step;
  7290. }
  7291. }
  7292. i--;
  7293. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7294. return new Curve3(catmullRom);
  7295. };
  7296. /**
  7297. * Returns the Curve3 stored array of successive Vector3
  7298. */
  7299. Curve3.prototype.getPoints = function () {
  7300. return this._points;
  7301. };
  7302. /**
  7303. * Returns the computed length (float) of the curve.
  7304. */
  7305. Curve3.prototype.length = function () {
  7306. return this._length;
  7307. };
  7308. /**
  7309. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7310. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7311. * curveA and curveB keep unchanged.
  7312. */
  7313. Curve3.prototype.continue = function (curve) {
  7314. var lastPoint = this._points[this._points.length - 1];
  7315. var continuedPoints = this._points.slice();
  7316. var curvePoints = curve.getPoints();
  7317. for (var i = 1; i < curvePoints.length; i++) {
  7318. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7319. }
  7320. var continuedCurve = new Curve3(continuedPoints);
  7321. return continuedCurve;
  7322. };
  7323. Curve3.prototype._computeLength = function (path) {
  7324. var l = 0;
  7325. for (var i = 1; i < path.length; i++) {
  7326. l += (path[i].subtract(path[i - 1])).length();
  7327. }
  7328. return l;
  7329. };
  7330. return Curve3;
  7331. }());
  7332. BABYLON.Curve3 = Curve3;
  7333. // Vertex formats
  7334. var PositionNormalVertex = /** @class */ (function () {
  7335. function PositionNormalVertex(position, normal) {
  7336. if (position === void 0) { position = Vector3.Zero(); }
  7337. if (normal === void 0) { normal = Vector3.Up(); }
  7338. this.position = position;
  7339. this.normal = normal;
  7340. }
  7341. PositionNormalVertex.prototype.clone = function () {
  7342. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7343. };
  7344. return PositionNormalVertex;
  7345. }());
  7346. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7347. var PositionNormalTextureVertex = /** @class */ (function () {
  7348. function PositionNormalTextureVertex(position, normal, uv) {
  7349. if (position === void 0) { position = Vector3.Zero(); }
  7350. if (normal === void 0) { normal = Vector3.Up(); }
  7351. if (uv === void 0) { uv = Vector2.Zero(); }
  7352. this.position = position;
  7353. this.normal = normal;
  7354. this.uv = uv;
  7355. }
  7356. PositionNormalTextureVertex.prototype.clone = function () {
  7357. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7358. };
  7359. return PositionNormalTextureVertex;
  7360. }());
  7361. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7362. // Temporary pre-allocated objects for engine internal use
  7363. // usage in any internal function :
  7364. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7365. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7366. var Tmp = /** @class */ (function () {
  7367. function Tmp() {
  7368. }
  7369. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7370. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7371. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7372. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7373. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7374. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7375. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7376. Matrix.Zero(), Matrix.Zero(),
  7377. Matrix.Zero(), Matrix.Zero(),
  7378. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7379. return Tmp;
  7380. }());
  7381. BABYLON.Tmp = Tmp;
  7382. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7383. var MathTmp = /** @class */ (function () {
  7384. function MathTmp() {
  7385. }
  7386. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7387. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7388. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7389. return MathTmp;
  7390. }());
  7391. })(BABYLON || (BABYLON = {}));
  7392. //# sourceMappingURL=babylon.math.js.map
  7393. var BABYLON;
  7394. (function (BABYLON) {
  7395. var Scalar = /** @class */ (function () {
  7396. function Scalar() {
  7397. }
  7398. /**
  7399. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7400. */
  7401. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7402. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7403. var num = a - b;
  7404. return -epsilon <= num && num <= epsilon;
  7405. };
  7406. /**
  7407. * Returns a string : the upper case translation of the number i to hexadecimal.
  7408. */
  7409. Scalar.ToHex = function (i) {
  7410. var str = i.toString(16);
  7411. if (i <= 15) {
  7412. return ("0" + str).toUpperCase();
  7413. }
  7414. return str.toUpperCase();
  7415. };
  7416. /**
  7417. * Returns -1 if value is negative and +1 is value is positive.
  7418. * Returns the value itself if it's equal to zero.
  7419. */
  7420. Scalar.Sign = function (value) {
  7421. value = +value; // convert to a number
  7422. if (value === 0 || isNaN(value))
  7423. return value;
  7424. return value > 0 ? 1 : -1;
  7425. };
  7426. /**
  7427. * Returns the value itself if it's between min and max.
  7428. * Returns min if the value is lower than min.
  7429. * Returns max if the value is greater than max.
  7430. */
  7431. Scalar.Clamp = function (value, min, max) {
  7432. if (min === void 0) { min = 0; }
  7433. if (max === void 0) { max = 1; }
  7434. return Math.min(max, Math.max(min, value));
  7435. };
  7436. /**
  7437. * Returns the log2 of value.
  7438. */
  7439. Scalar.Log2 = function (value) {
  7440. return Math.log(value) * Math.LOG2E;
  7441. };
  7442. /**
  7443. * Loops the value, so that it is never larger than length and never smaller than 0.
  7444. *
  7445. * This is similar to the modulo operator but it works with floating point numbers.
  7446. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7447. * With t = 5 and length = 2.5, the result would be 0.0.
  7448. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7449. */
  7450. Scalar.Repeat = function (value, length) {
  7451. return value - Math.floor(value / length) * length;
  7452. };
  7453. /**
  7454. * Normalize the value between 0.0 and 1.0 using min and max values
  7455. */
  7456. Scalar.Normalize = function (value, min, max) {
  7457. return (value - min) / (max - min);
  7458. };
  7459. /**
  7460. * Denormalize the value from 0.0 and 1.0 using min and max values
  7461. */
  7462. Scalar.Denormalize = function (normalized, min, max) {
  7463. return (normalized * (max - min) + min);
  7464. };
  7465. /**
  7466. * Calculates the shortest difference between two given angles given in degrees.
  7467. */
  7468. Scalar.DeltaAngle = function (current, target) {
  7469. var num = Scalar.Repeat(target - current, 360.0);
  7470. if (num > 180.0) {
  7471. num -= 360.0;
  7472. }
  7473. return num;
  7474. };
  7475. /**
  7476. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7477. *
  7478. * The returned value will move back and forth between 0 and length
  7479. */
  7480. Scalar.PingPong = function (tx, length) {
  7481. var t = Scalar.Repeat(tx, length * 2.0);
  7482. return length - Math.abs(t - length);
  7483. };
  7484. /**
  7485. * Interpolates between min and max with smoothing at the limits.
  7486. *
  7487. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7488. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7489. */
  7490. Scalar.SmoothStep = function (from, to, tx) {
  7491. var t = Scalar.Clamp(tx);
  7492. t = -2.0 * t * t * t + 3.0 * t * t;
  7493. return to * t + from * (1.0 - t);
  7494. };
  7495. /**
  7496. * Moves a value current towards target.
  7497. *
  7498. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7499. * Negative values of maxDelta pushes the value away from target.
  7500. */
  7501. Scalar.MoveTowards = function (current, target, maxDelta) {
  7502. var result = 0;
  7503. if (Math.abs(target - current) <= maxDelta) {
  7504. result = target;
  7505. }
  7506. else {
  7507. result = current + Scalar.Sign(target - current) * maxDelta;
  7508. }
  7509. return result;
  7510. };
  7511. /**
  7512. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7513. *
  7514. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7515. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7516. */
  7517. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7518. var num = Scalar.DeltaAngle(current, target);
  7519. var result = 0;
  7520. if (-maxDelta < num && num < maxDelta) {
  7521. result = target;
  7522. }
  7523. else {
  7524. target = current + num;
  7525. result = Scalar.MoveTowards(current, target, maxDelta);
  7526. }
  7527. return result;
  7528. };
  7529. /**
  7530. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7531. */
  7532. Scalar.Lerp = function (start, end, amount) {
  7533. return start + ((end - start) * amount);
  7534. };
  7535. /**
  7536. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7537. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7538. */
  7539. Scalar.LerpAngle = function (start, end, amount) {
  7540. var num = Scalar.Repeat(end - start, 360.0);
  7541. if (num > 180.0) {
  7542. num -= 360.0;
  7543. }
  7544. return start + num * Scalar.Clamp(amount);
  7545. };
  7546. /**
  7547. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7548. */
  7549. Scalar.InverseLerp = function (a, b, value) {
  7550. var result = 0;
  7551. if (a != b) {
  7552. result = Scalar.Clamp((value - a) / (b - a));
  7553. }
  7554. else {
  7555. result = 0.0;
  7556. }
  7557. return result;
  7558. };
  7559. /**
  7560. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7561. */
  7562. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7563. var squared = amount * amount;
  7564. var cubed = amount * squared;
  7565. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7566. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7567. var part3 = (cubed - (2.0 * squared)) + amount;
  7568. var part4 = cubed - squared;
  7569. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7570. };
  7571. /**
  7572. * Returns a random float number between and min and max values
  7573. */
  7574. Scalar.RandomRange = function (min, max) {
  7575. if (min === max)
  7576. return min;
  7577. return ((Math.random() * (max - min)) + min);
  7578. };
  7579. /**
  7580. * This function returns percentage of a number in a given range.
  7581. *
  7582. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7583. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7584. */
  7585. Scalar.RangeToPercent = function (number, min, max) {
  7586. return ((number - min) / (max - min));
  7587. };
  7588. /**
  7589. * This function returns number that corresponds to the percentage in a given range.
  7590. *
  7591. * PercentToRange(0.34,0,100) will return 34.
  7592. */
  7593. Scalar.PercentToRange = function (percent, min, max) {
  7594. return ((max - min) * percent + min);
  7595. };
  7596. /**
  7597. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7598. * @param angle The angle to normalize in radian.
  7599. * @return The converted angle.
  7600. */
  7601. Scalar.NormalizeRadians = function (angle) {
  7602. // More precise but slower version kept for reference.
  7603. // angle = angle % Tools.TwoPi;
  7604. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7605. //if (angle > Math.PI) {
  7606. // angle -= Tools.TwoPi;
  7607. //}
  7608. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7609. return angle;
  7610. };
  7611. /**
  7612. * Two pi constants convenient for computation.
  7613. */
  7614. Scalar.TwoPi = Math.PI * 2;
  7615. return Scalar;
  7616. }());
  7617. BABYLON.Scalar = Scalar;
  7618. })(BABYLON || (BABYLON = {}));
  7619. //# sourceMappingURL=babylon.math.scalar.js.map
  7620. //# sourceMappingURL=babylon.mixins.js.map
  7621. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7622. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7623. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7624. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7625. //# sourceMappingURL=babylon.webgl2.js.map
  7626. var BABYLON;
  7627. (function (BABYLON) {
  7628. var __decoratorInitialStore = {};
  7629. var __mergedStore = {};
  7630. var _copySource = function (creationFunction, source, instanciate) {
  7631. var destination = creationFunction();
  7632. // Tags
  7633. if (BABYLON.Tags) {
  7634. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7635. }
  7636. var classStore = getMergedStore(destination);
  7637. // Properties
  7638. for (var property in classStore) {
  7639. var propertyDescriptor = classStore[property];
  7640. var sourceProperty = source[property];
  7641. var propertyType = propertyDescriptor.type;
  7642. if (sourceProperty !== undefined && sourceProperty !== null) {
  7643. switch (propertyType) {
  7644. case 0: // Value
  7645. case 6: // Mesh reference
  7646. case 11: // Camera reference
  7647. destination[property] = sourceProperty;
  7648. break;
  7649. case 1: // Texture
  7650. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7651. break;
  7652. case 2: // Color3
  7653. case 3: // FresnelParameters
  7654. case 4: // Vector2
  7655. case 5: // Vector3
  7656. case 7: // Color Curves
  7657. case 10: // Quaternion
  7658. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7659. break;
  7660. }
  7661. }
  7662. }
  7663. return destination;
  7664. };
  7665. function getDirectStore(target) {
  7666. var classKey = target.getClassName();
  7667. if (!__decoratorInitialStore[classKey]) {
  7668. __decoratorInitialStore[classKey] = {};
  7669. }
  7670. return __decoratorInitialStore[classKey];
  7671. }
  7672. /**
  7673. * Return the list of properties flagged as serializable
  7674. * @param target: host object
  7675. */
  7676. function getMergedStore(target) {
  7677. var classKey = target.getClassName();
  7678. if (__mergedStore[classKey]) {
  7679. return __mergedStore[classKey];
  7680. }
  7681. __mergedStore[classKey] = {};
  7682. var store = __mergedStore[classKey];
  7683. var currentTarget = target;
  7684. var currentKey = classKey;
  7685. while (currentKey) {
  7686. var initialStore = __decoratorInitialStore[currentKey];
  7687. for (var property in initialStore) {
  7688. store[property] = initialStore[property];
  7689. }
  7690. var parent_1 = void 0;
  7691. var done = false;
  7692. do {
  7693. parent_1 = Object.getPrototypeOf(currentTarget);
  7694. if (!parent_1.getClassName) {
  7695. done = true;
  7696. break;
  7697. }
  7698. if (parent_1.getClassName() !== currentKey) {
  7699. break;
  7700. }
  7701. currentTarget = parent_1;
  7702. } while (parent_1);
  7703. if (done) {
  7704. break;
  7705. }
  7706. currentKey = parent_1.getClassName();
  7707. currentTarget = parent_1;
  7708. }
  7709. return store;
  7710. }
  7711. function generateSerializableMember(type, sourceName) {
  7712. return function (target, propertyKey) {
  7713. var classStore = getDirectStore(target);
  7714. if (!classStore[propertyKey]) {
  7715. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7716. }
  7717. };
  7718. }
  7719. function generateExpandMember(setCallback, targetKey) {
  7720. if (targetKey === void 0) { targetKey = null; }
  7721. return function (target, propertyKey) {
  7722. var key = targetKey || ("_" + propertyKey);
  7723. Object.defineProperty(target, propertyKey, {
  7724. get: function () {
  7725. return this[key];
  7726. },
  7727. set: function (value) {
  7728. if (this[key] === value) {
  7729. return;
  7730. }
  7731. this[key] = value;
  7732. target[setCallback].apply(this);
  7733. },
  7734. enumerable: true,
  7735. configurable: true
  7736. });
  7737. };
  7738. }
  7739. function expandToProperty(callback, targetKey) {
  7740. if (targetKey === void 0) { targetKey = null; }
  7741. return generateExpandMember(callback, targetKey);
  7742. }
  7743. BABYLON.expandToProperty = expandToProperty;
  7744. function serialize(sourceName) {
  7745. return generateSerializableMember(0, sourceName); // value member
  7746. }
  7747. BABYLON.serialize = serialize;
  7748. function serializeAsTexture(sourceName) {
  7749. return generateSerializableMember(1, sourceName); // texture member
  7750. }
  7751. BABYLON.serializeAsTexture = serializeAsTexture;
  7752. function serializeAsColor3(sourceName) {
  7753. return generateSerializableMember(2, sourceName); // color3 member
  7754. }
  7755. BABYLON.serializeAsColor3 = serializeAsColor3;
  7756. function serializeAsFresnelParameters(sourceName) {
  7757. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7758. }
  7759. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7760. function serializeAsVector2(sourceName) {
  7761. return generateSerializableMember(4, sourceName); // vector2 member
  7762. }
  7763. BABYLON.serializeAsVector2 = serializeAsVector2;
  7764. function serializeAsVector3(sourceName) {
  7765. return generateSerializableMember(5, sourceName); // vector3 member
  7766. }
  7767. BABYLON.serializeAsVector3 = serializeAsVector3;
  7768. function serializeAsMeshReference(sourceName) {
  7769. return generateSerializableMember(6, sourceName); // mesh reference member
  7770. }
  7771. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7772. function serializeAsColorCurves(sourceName) {
  7773. return generateSerializableMember(7, sourceName); // color curves
  7774. }
  7775. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7776. function serializeAsColor4(sourceName) {
  7777. return generateSerializableMember(8, sourceName); // color 4
  7778. }
  7779. BABYLON.serializeAsColor4 = serializeAsColor4;
  7780. function serializeAsImageProcessingConfiguration(sourceName) {
  7781. return generateSerializableMember(9, sourceName); // image processing
  7782. }
  7783. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7784. function serializeAsQuaternion(sourceName) {
  7785. return generateSerializableMember(10, sourceName); // quaternion member
  7786. }
  7787. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7788. /**
  7789. * Decorator used to define property that can be serialized as reference to a camera
  7790. * @param sourceName defines the name of the property to decorate
  7791. */
  7792. function serializeAsCameraReference(sourceName) {
  7793. return generateSerializableMember(11, sourceName); // camera reference member
  7794. }
  7795. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7796. var SerializationHelper = /** @class */ (function () {
  7797. function SerializationHelper() {
  7798. }
  7799. SerializationHelper.Serialize = function (entity, serializationObject) {
  7800. if (!serializationObject) {
  7801. serializationObject = {};
  7802. }
  7803. // Tags
  7804. if (BABYLON.Tags) {
  7805. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7806. }
  7807. var serializedProperties = getMergedStore(entity);
  7808. // Properties
  7809. for (var property in serializedProperties) {
  7810. var propertyDescriptor = serializedProperties[property];
  7811. var targetPropertyName = propertyDescriptor.sourceName || property;
  7812. var propertyType = propertyDescriptor.type;
  7813. var sourceProperty = entity[property];
  7814. if (sourceProperty !== undefined && sourceProperty !== null) {
  7815. switch (propertyType) {
  7816. case 0: // Value
  7817. serializationObject[targetPropertyName] = sourceProperty;
  7818. break;
  7819. case 1: // Texture
  7820. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7821. break;
  7822. case 2: // Color3
  7823. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7824. break;
  7825. case 3: // FresnelParameters
  7826. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7827. break;
  7828. case 4: // Vector2
  7829. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7830. break;
  7831. case 5: // Vector3
  7832. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7833. break;
  7834. case 6: // Mesh reference
  7835. serializationObject[targetPropertyName] = sourceProperty.id;
  7836. break;
  7837. case 7: // Color Curves
  7838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7839. break;
  7840. case 8: // Color 4
  7841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7842. break;
  7843. case 9: // Image Processing
  7844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7845. break;
  7846. case 10: // Quaternion
  7847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7848. break;
  7849. case 11: // Camera reference
  7850. serializationObject[targetPropertyName] = sourceProperty.id;
  7851. break;
  7852. }
  7853. }
  7854. }
  7855. return serializationObject;
  7856. };
  7857. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7858. if (rootUrl === void 0) { rootUrl = null; }
  7859. var destination = creationFunction();
  7860. if (!rootUrl) {
  7861. rootUrl = "";
  7862. }
  7863. // Tags
  7864. if (BABYLON.Tags) {
  7865. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7866. }
  7867. var classStore = getMergedStore(destination);
  7868. // Properties
  7869. for (var property in classStore) {
  7870. var propertyDescriptor = classStore[property];
  7871. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7872. var propertyType = propertyDescriptor.type;
  7873. if (sourceProperty !== undefined && sourceProperty !== null) {
  7874. var dest = destination;
  7875. switch (propertyType) {
  7876. case 0: // Value
  7877. dest[property] = sourceProperty;
  7878. break;
  7879. case 1: // Texture
  7880. if (scene) {
  7881. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7882. }
  7883. break;
  7884. case 2: // Color3
  7885. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7886. break;
  7887. case 3: // FresnelParameters
  7888. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7889. break;
  7890. case 4: // Vector2
  7891. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7892. break;
  7893. case 5: // Vector3
  7894. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7895. break;
  7896. case 6: // Mesh reference
  7897. if (scene) {
  7898. dest[property] = scene.getLastMeshByID(sourceProperty);
  7899. }
  7900. break;
  7901. case 7: // Color Curves
  7902. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7903. break;
  7904. case 8: // Color 4
  7905. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7906. break;
  7907. case 9: // Image Processing
  7908. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7909. break;
  7910. case 10: // Quaternion
  7911. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7912. break;
  7913. case 11: // Camera reference
  7914. if (scene) {
  7915. dest[property] = scene.getCameraByID(sourceProperty);
  7916. }
  7917. break;
  7918. }
  7919. }
  7920. }
  7921. return destination;
  7922. };
  7923. SerializationHelper.Clone = function (creationFunction, source) {
  7924. return _copySource(creationFunction, source, false);
  7925. };
  7926. SerializationHelper.Instanciate = function (creationFunction, source) {
  7927. return _copySource(creationFunction, source, true);
  7928. };
  7929. return SerializationHelper;
  7930. }());
  7931. BABYLON.SerializationHelper = SerializationHelper;
  7932. })(BABYLON || (BABYLON = {}));
  7933. //# sourceMappingURL=babylon.decorators.js.map
  7934. var BABYLON;
  7935. (function (BABYLON) {
  7936. /**
  7937. * Wrapper class for promise with external resolve and reject.
  7938. */
  7939. var Deferred = /** @class */ (function () {
  7940. /**
  7941. * Constructor for this deferred object.
  7942. */
  7943. function Deferred() {
  7944. var _this = this;
  7945. this.promise = new Promise(function (resolve, reject) {
  7946. _this._resolve = resolve;
  7947. _this._reject = reject;
  7948. });
  7949. }
  7950. Object.defineProperty(Deferred.prototype, "resolve", {
  7951. /**
  7952. * The resolve method of the promise associated with this deferred object.
  7953. */
  7954. get: function () {
  7955. return this._resolve;
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(Deferred.prototype, "reject", {
  7961. /**
  7962. * The reject method of the promise associated with this deferred object.
  7963. */
  7964. get: function () {
  7965. return this._reject;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. return Deferred;
  7971. }());
  7972. BABYLON.Deferred = Deferred;
  7973. })(BABYLON || (BABYLON = {}));
  7974. //# sourceMappingURL=babylon.deferred.js.map
  7975. var BABYLON;
  7976. (function (BABYLON) {
  7977. /**
  7978. * A class serves as a medium between the observable and its observers
  7979. */
  7980. var EventState = /** @class */ (function () {
  7981. /**
  7982. * Create a new EventState
  7983. * @param mask defines the mask associated with this state
  7984. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7985. * @param target defines the original target of the state
  7986. * @param currentTarget defines the current target of the state
  7987. */
  7988. function EventState(mask, skipNextObservers, target, currentTarget) {
  7989. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7990. this.initalize(mask, skipNextObservers, target, currentTarget);
  7991. }
  7992. /**
  7993. * Initialize the current event state
  7994. * @param mask defines the mask associated with this state
  7995. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7996. * @param target defines the original target of the state
  7997. * @param currentTarget defines the current target of the state
  7998. * @returns the current event state
  7999. */
  8000. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8001. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8002. this.mask = mask;
  8003. this.skipNextObservers = skipNextObservers;
  8004. this.target = target;
  8005. this.currentTarget = currentTarget;
  8006. return this;
  8007. };
  8008. return EventState;
  8009. }());
  8010. BABYLON.EventState = EventState;
  8011. /**
  8012. * Represent an Observer registered to a given Observable object.
  8013. */
  8014. var Observer = /** @class */ (function () {
  8015. /**
  8016. * Creates a new observer
  8017. * @param callback defines the callback to call when the observer is notified
  8018. * @param mask defines the mask of the observer (used to filter notifications)
  8019. * @param scope defines the current scope used to restore the JS context
  8020. */
  8021. function Observer(
  8022. /**
  8023. * Defines the callback to call when the observer is notified
  8024. */
  8025. callback,
  8026. /**
  8027. * Defines the mask of the observer (used to filter notifications)
  8028. */
  8029. mask,
  8030. /**
  8031. * Defines the current scope used to restore the JS context
  8032. */
  8033. scope) {
  8034. if (scope === void 0) { scope = null; }
  8035. this.callback = callback;
  8036. this.mask = mask;
  8037. this.scope = scope;
  8038. /** @hidden */
  8039. this._willBeUnregistered = false;
  8040. /**
  8041. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8042. */
  8043. this.unregisterOnNextCall = false;
  8044. }
  8045. return Observer;
  8046. }());
  8047. BABYLON.Observer = Observer;
  8048. /**
  8049. * Represent a list of observers registered to multiple Observables object.
  8050. */
  8051. var MultiObserver = /** @class */ (function () {
  8052. function MultiObserver() {
  8053. }
  8054. /**
  8055. * Release associated resources
  8056. */
  8057. MultiObserver.prototype.dispose = function () {
  8058. if (this._observers && this._observables) {
  8059. for (var index = 0; index < this._observers.length; index++) {
  8060. this._observables[index].remove(this._observers[index]);
  8061. }
  8062. }
  8063. this._observers = null;
  8064. this._observables = null;
  8065. };
  8066. /**
  8067. * Raise a callback when one of the observable will notify
  8068. * @param observables defines a list of observables to watch
  8069. * @param callback defines the callback to call on notification
  8070. * @param mask defines the mask used to filter notifications
  8071. * @param scope defines the current scope used to restore the JS context
  8072. * @returns the new MultiObserver
  8073. */
  8074. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8075. if (mask === void 0) { mask = -1; }
  8076. if (scope === void 0) { scope = null; }
  8077. var result = new MultiObserver();
  8078. result._observers = new Array();
  8079. result._observables = observables;
  8080. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8081. var observable = observables_1[_i];
  8082. var observer = observable.add(callback, mask, false, scope);
  8083. if (observer) {
  8084. result._observers.push(observer);
  8085. }
  8086. }
  8087. return result;
  8088. };
  8089. return MultiObserver;
  8090. }());
  8091. BABYLON.MultiObserver = MultiObserver;
  8092. /**
  8093. * The Observable class is a simple implementation of the Observable pattern.
  8094. *
  8095. * 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.
  8096. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8097. * 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).
  8098. * 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.
  8099. */
  8100. var Observable = /** @class */ (function () {
  8101. /**
  8102. * Creates a new observable
  8103. * @param onObserverAdded defines a callback to call when a new observer is added
  8104. */
  8105. function Observable(onObserverAdded) {
  8106. this._observers = new Array();
  8107. this._eventState = new EventState(0);
  8108. if (onObserverAdded) {
  8109. this._onObserverAdded = onObserverAdded;
  8110. }
  8111. }
  8112. /**
  8113. * Create a new Observer with the specified callback
  8114. * @param callback the callback that will be executed for that Observer
  8115. * @param mask the mask used to filter observers
  8116. * @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.
  8117. * @param scope optional scope for the callback to be called from
  8118. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8119. * @returns the new observer created for the callback
  8120. */
  8121. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8122. if (mask === void 0) { mask = -1; }
  8123. if (insertFirst === void 0) { insertFirst = false; }
  8124. if (scope === void 0) { scope = null; }
  8125. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8126. if (!callback) {
  8127. return null;
  8128. }
  8129. var observer = new Observer(callback, mask, scope);
  8130. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8131. if (insertFirst) {
  8132. this._observers.unshift(observer);
  8133. }
  8134. else {
  8135. this._observers.push(observer);
  8136. }
  8137. if (this._onObserverAdded) {
  8138. this._onObserverAdded(observer);
  8139. }
  8140. return observer;
  8141. };
  8142. /**
  8143. * Remove an Observer from the Observable object
  8144. * @param observer the instance of the Observer to remove
  8145. * @returns false if it doesn't belong to this Observable
  8146. */
  8147. Observable.prototype.remove = function (observer) {
  8148. if (!observer) {
  8149. return false;
  8150. }
  8151. var index = this._observers.indexOf(observer);
  8152. if (index !== -1) {
  8153. this._observers.splice(index, 1);
  8154. return true;
  8155. }
  8156. return false;
  8157. };
  8158. /**
  8159. * Remove a callback from the Observable object
  8160. * @param callback the callback to remove
  8161. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8162. * @returns false if it doesn't belong to this Observable
  8163. */
  8164. Observable.prototype.removeCallback = function (callback, scope) {
  8165. for (var index = 0; index < this._observers.length; index++) {
  8166. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8167. this._observers.splice(index, 1);
  8168. return true;
  8169. }
  8170. }
  8171. return false;
  8172. };
  8173. Observable.prototype._deferUnregister = function (observer) {
  8174. var _this = this;
  8175. observer.unregisterOnNextCall = false;
  8176. observer._willBeUnregistered = true;
  8177. BABYLON.Tools.SetImmediate(function () {
  8178. _this.remove(observer);
  8179. });
  8180. };
  8181. /**
  8182. * Notify all Observers by calling their respective callback with the given data
  8183. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8184. * @param eventData defines the data to send to all observers
  8185. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8186. * @param target defines the original target of the state
  8187. * @param currentTarget defines the current target of the state
  8188. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8189. */
  8190. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8191. if (mask === void 0) { mask = -1; }
  8192. if (!this._observers.length) {
  8193. return true;
  8194. }
  8195. var state = this._eventState;
  8196. state.mask = mask;
  8197. state.target = target;
  8198. state.currentTarget = currentTarget;
  8199. state.skipNextObservers = false;
  8200. state.lastReturnValue = eventData;
  8201. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8202. var obs = _a[_i];
  8203. if (obs._willBeUnregistered) {
  8204. continue;
  8205. }
  8206. if (obs.mask & mask) {
  8207. if (obs.scope) {
  8208. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8209. }
  8210. else {
  8211. state.lastReturnValue = obs.callback(eventData, state);
  8212. }
  8213. if (obs.unregisterOnNextCall) {
  8214. this._deferUnregister(obs);
  8215. }
  8216. }
  8217. if (state.skipNextObservers) {
  8218. return false;
  8219. }
  8220. }
  8221. return true;
  8222. };
  8223. /**
  8224. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8225. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8226. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8227. * and it is crucial that all callbacks will be executed.
  8228. * The order of the callbacks is kept, callbacks are not executed parallel.
  8229. *
  8230. * @param eventData The data to be sent to each callback
  8231. * @param mask is used to filter observers defaults to -1
  8232. * @param target defines the callback target (see EventState)
  8233. * @param currentTarget defines he current object in the bubbling phase
  8234. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8235. */
  8236. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8237. var _this = this;
  8238. if (mask === void 0) { mask = -1; }
  8239. // create an empty promise
  8240. var p = Promise.resolve(eventData);
  8241. // no observers? return this promise.
  8242. if (!this._observers.length) {
  8243. return p;
  8244. }
  8245. var state = this._eventState;
  8246. state.mask = mask;
  8247. state.target = target;
  8248. state.currentTarget = currentTarget;
  8249. state.skipNextObservers = false;
  8250. // execute one callback after another (not using Promise.all, the order is important)
  8251. this._observers.forEach(function (obs) {
  8252. if (state.skipNextObservers) {
  8253. return;
  8254. }
  8255. if (obs._willBeUnregistered) {
  8256. return;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. p = p.then(function (lastReturnedValue) {
  8261. state.lastReturnValue = lastReturnedValue;
  8262. return obs.callback.apply(obs.scope, [eventData, state]);
  8263. });
  8264. }
  8265. else {
  8266. p = p.then(function (lastReturnedValue) {
  8267. state.lastReturnValue = lastReturnedValue;
  8268. return obs.callback(eventData, state);
  8269. });
  8270. }
  8271. if (obs.unregisterOnNextCall) {
  8272. _this._deferUnregister(obs);
  8273. }
  8274. }
  8275. });
  8276. // return the eventData
  8277. return p.then(function () { return eventData; });
  8278. };
  8279. /**
  8280. * Notify a specific observer
  8281. * @param observer defines the observer to notify
  8282. * @param eventData defines the data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. */
  8285. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8286. if (mask === void 0) { mask = -1; }
  8287. var state = this._eventState;
  8288. state.mask = mask;
  8289. state.skipNextObservers = false;
  8290. observer.callback(eventData, state);
  8291. };
  8292. /**
  8293. * Gets a boolean indicating if the observable has at least one observer
  8294. * @returns true is the Observable has at least one Observer registered
  8295. */
  8296. Observable.prototype.hasObservers = function () {
  8297. return this._observers.length > 0;
  8298. };
  8299. /**
  8300. * Clear the list of observers
  8301. */
  8302. Observable.prototype.clear = function () {
  8303. this._observers = new Array();
  8304. this._onObserverAdded = null;
  8305. };
  8306. /**
  8307. * Clone the current observable
  8308. * @returns a new observable
  8309. */
  8310. Observable.prototype.clone = function () {
  8311. var result = new Observable();
  8312. result._observers = this._observers.slice(0);
  8313. return result;
  8314. };
  8315. /**
  8316. * Does this observable handles observer registered with a given mask
  8317. * @param mask defines the mask to be tested
  8318. * @return whether or not one observer registered with the given mask is handeled
  8319. **/
  8320. Observable.prototype.hasSpecificMask = function (mask) {
  8321. if (mask === void 0) { mask = -1; }
  8322. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8323. var obs = _a[_i];
  8324. if (obs.mask & mask || obs.mask === mask) {
  8325. return true;
  8326. }
  8327. }
  8328. return false;
  8329. };
  8330. return Observable;
  8331. }());
  8332. BABYLON.Observable = Observable;
  8333. })(BABYLON || (BABYLON = {}));
  8334. //# sourceMappingURL=babylon.observable.js.map
  8335. var BABYLON;
  8336. (function (BABYLON) {
  8337. var SmartArray = /** @class */ (function () {
  8338. function SmartArray(capacity) {
  8339. this.length = 0;
  8340. this.data = new Array(capacity);
  8341. this._id = SmartArray._GlobalId++;
  8342. }
  8343. SmartArray.prototype.push = function (value) {
  8344. this.data[this.length++] = value;
  8345. if (this.length > this.data.length) {
  8346. this.data.length *= 2;
  8347. }
  8348. };
  8349. SmartArray.prototype.forEach = function (func) {
  8350. for (var index = 0; index < this.length; index++) {
  8351. func(this.data[index]);
  8352. }
  8353. };
  8354. SmartArray.prototype.sort = function (compareFn) {
  8355. this.data.sort(compareFn);
  8356. };
  8357. SmartArray.prototype.reset = function () {
  8358. this.length = 0;
  8359. };
  8360. SmartArray.prototype.dispose = function () {
  8361. this.reset();
  8362. if (this.data) {
  8363. this.data.length = 0;
  8364. this.data = [];
  8365. }
  8366. };
  8367. SmartArray.prototype.concat = function (array) {
  8368. if (array.length === 0) {
  8369. return;
  8370. }
  8371. if (this.length + array.length > this.data.length) {
  8372. this.data.length = (this.length + array.length) * 2;
  8373. }
  8374. for (var index = 0; index < array.length; index++) {
  8375. this.data[this.length++] = (array.data || array)[index];
  8376. }
  8377. };
  8378. SmartArray.prototype.indexOf = function (value) {
  8379. var position = this.data.indexOf(value);
  8380. if (position >= this.length) {
  8381. return -1;
  8382. }
  8383. return position;
  8384. };
  8385. SmartArray.prototype.contains = function (value) {
  8386. return this.data.indexOf(value) !== -1;
  8387. };
  8388. // Statics
  8389. SmartArray._GlobalId = 0;
  8390. return SmartArray;
  8391. }());
  8392. BABYLON.SmartArray = SmartArray;
  8393. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8394. __extends(SmartArrayNoDuplicate, _super);
  8395. function SmartArrayNoDuplicate() {
  8396. var _this = _super !== null && _super.apply(this, arguments) || this;
  8397. _this._duplicateId = 0;
  8398. return _this;
  8399. }
  8400. SmartArrayNoDuplicate.prototype.push = function (value) {
  8401. _super.prototype.push.call(this, value);
  8402. if (!value.__smartArrayFlags) {
  8403. value.__smartArrayFlags = {};
  8404. }
  8405. value.__smartArrayFlags[this._id] = this._duplicateId;
  8406. };
  8407. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8408. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8409. return false;
  8410. }
  8411. this.push(value);
  8412. return true;
  8413. };
  8414. SmartArrayNoDuplicate.prototype.reset = function () {
  8415. _super.prototype.reset.call(this);
  8416. this._duplicateId++;
  8417. };
  8418. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8419. if (array.length === 0) {
  8420. return;
  8421. }
  8422. if (this.length + array.length > this.data.length) {
  8423. this.data.length = (this.length + array.length) * 2;
  8424. }
  8425. for (var index = 0; index < array.length; index++) {
  8426. var item = (array.data || array)[index];
  8427. this.pushNoDuplicate(item);
  8428. }
  8429. };
  8430. return SmartArrayNoDuplicate;
  8431. }(SmartArray));
  8432. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8433. })(BABYLON || (BABYLON = {}));
  8434. //# sourceMappingURL=babylon.smartArray.js.map
  8435. var BABYLON;
  8436. (function (BABYLON) {
  8437. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8438. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8439. var LoadFileError = /** @class */ (function (_super) {
  8440. __extends(LoadFileError, _super);
  8441. function LoadFileError(message, request) {
  8442. var _this = _super.call(this, message) || this;
  8443. _this.request = request;
  8444. _this.name = "LoadFileError";
  8445. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8446. return _this;
  8447. }
  8448. // Polyfill for Object.setPrototypeOf if necessary.
  8449. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8450. return LoadFileError;
  8451. }(Error));
  8452. BABYLON.LoadFileError = LoadFileError;
  8453. var RetryStrategy = /** @class */ (function () {
  8454. function RetryStrategy() {
  8455. }
  8456. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8457. if (maxRetries === void 0) { maxRetries = 3; }
  8458. if (baseInterval === void 0) { baseInterval = 500; }
  8459. return function (url, request, retryIndex) {
  8460. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8461. return -1;
  8462. }
  8463. return Math.pow(2, retryIndex) * baseInterval;
  8464. };
  8465. };
  8466. return RetryStrategy;
  8467. }());
  8468. BABYLON.RetryStrategy = RetryStrategy;
  8469. // Screenshots
  8470. var screenshotCanvas;
  8471. var cloneValue = function (source, destinationObject) {
  8472. if (!source)
  8473. return null;
  8474. if (source instanceof BABYLON.Mesh) {
  8475. return null;
  8476. }
  8477. if (source instanceof BABYLON.SubMesh) {
  8478. return source.clone(destinationObject);
  8479. }
  8480. else if (source.clone) {
  8481. return source.clone();
  8482. }
  8483. return null;
  8484. };
  8485. var Tools = /** @class */ (function () {
  8486. function Tools() {
  8487. }
  8488. /**
  8489. * Interpolates between a and b via alpha
  8490. * @param a The lower value (returned when alpha = 0)
  8491. * @param b The upper value (returned when alpha = 1)
  8492. * @param alpha The interpolation-factor
  8493. * @return The mixed value
  8494. */
  8495. Tools.Mix = function (a, b, alpha) {
  8496. return a * (1 - alpha) + b * alpha;
  8497. };
  8498. Tools.Instantiate = function (className) {
  8499. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8500. return Tools.RegisteredExternalClasses[className];
  8501. }
  8502. var arr = className.split(".");
  8503. var fn = (window || this);
  8504. for (var i = 0, len = arr.length; i < len; i++) {
  8505. fn = fn[arr[i]];
  8506. }
  8507. if (typeof fn !== "function") {
  8508. return null;
  8509. }
  8510. return fn;
  8511. };
  8512. /**
  8513. * Provides a slice function that will work even on IE
  8514. * @param data defines the array to slice
  8515. * @param start defines the start of the data (optional)
  8516. * @param end defines the end of the data (optional)
  8517. * @returns the new sliced array
  8518. */
  8519. Tools.Slice = function (data, start, end) {
  8520. if (data.slice) {
  8521. return data.slice(start, end);
  8522. }
  8523. return Array.prototype.slice.call(data, start, end);
  8524. };
  8525. Tools.SetImmediate = function (action) {
  8526. if (window.setImmediate) {
  8527. window.setImmediate(action);
  8528. }
  8529. else {
  8530. setTimeout(action, 1);
  8531. }
  8532. };
  8533. Tools.IsExponentOfTwo = function (value) {
  8534. var count = 1;
  8535. do {
  8536. count *= 2;
  8537. } while (count < value);
  8538. return count === value;
  8539. };
  8540. /**
  8541. * Returns the nearest 32-bit single precision float representation of a Number
  8542. * @param value A Number. If the parameter is of a different type, it will get converted
  8543. * to a number or to NaN if it cannot be converted
  8544. * @returns number
  8545. */
  8546. Tools.FloatRound = function (value) {
  8547. if (Math.fround) {
  8548. return Math.fround(value);
  8549. }
  8550. return (Tools._tmpFloatArray[0] = value);
  8551. };
  8552. /**
  8553. * Find the next highest power of two.
  8554. * @param x Number to start search from.
  8555. * @return Next highest power of two.
  8556. */
  8557. Tools.CeilingPOT = function (x) {
  8558. x--;
  8559. x |= x >> 1;
  8560. x |= x >> 2;
  8561. x |= x >> 4;
  8562. x |= x >> 8;
  8563. x |= x >> 16;
  8564. x++;
  8565. return x;
  8566. };
  8567. /**
  8568. * Find the next lowest power of two.
  8569. * @param x Number to start search from.
  8570. * @return Next lowest power of two.
  8571. */
  8572. Tools.FloorPOT = function (x) {
  8573. x = x | (x >> 1);
  8574. x = x | (x >> 2);
  8575. x = x | (x >> 4);
  8576. x = x | (x >> 8);
  8577. x = x | (x >> 16);
  8578. return x - (x >> 1);
  8579. };
  8580. /**
  8581. * Find the nearest power of two.
  8582. * @param x Number to start search from.
  8583. * @return Next nearest power of two.
  8584. */
  8585. Tools.NearestPOT = function (x) {
  8586. var c = Tools.CeilingPOT(x);
  8587. var f = Tools.FloorPOT(x);
  8588. return (c - x) > (x - f) ? f : c;
  8589. };
  8590. Tools.GetExponentOfTwo = function (value, max, mode) {
  8591. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8592. var pot;
  8593. switch (mode) {
  8594. case BABYLON.Engine.SCALEMODE_FLOOR:
  8595. pot = Tools.FloorPOT(value);
  8596. break;
  8597. case BABYLON.Engine.SCALEMODE_NEAREST:
  8598. pot = Tools.NearestPOT(value);
  8599. break;
  8600. case BABYLON.Engine.SCALEMODE_CEILING:
  8601. default:
  8602. pot = Tools.CeilingPOT(value);
  8603. break;
  8604. }
  8605. return Math.min(pot, max);
  8606. };
  8607. Tools.GetFilename = function (path) {
  8608. var index = path.lastIndexOf("/");
  8609. if (index < 0)
  8610. return path;
  8611. return path.substring(index + 1);
  8612. };
  8613. /**
  8614. * Extracts the "folder" part of a path (everything before the filename).
  8615. * @param uri The URI to extract the info from
  8616. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8617. * @returns The "folder" part of the path
  8618. */
  8619. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8620. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8621. var index = uri.lastIndexOf("/");
  8622. if (index < 0) {
  8623. if (returnUnchangedIfNoSlash) {
  8624. return uri;
  8625. }
  8626. return "";
  8627. }
  8628. return uri.substring(0, index + 1);
  8629. };
  8630. Tools.GetDOMTextContent = function (element) {
  8631. var result = "";
  8632. var child = element.firstChild;
  8633. while (child) {
  8634. if (child.nodeType === 3) {
  8635. result += child.textContent;
  8636. }
  8637. child = child.nextSibling;
  8638. }
  8639. return result;
  8640. };
  8641. Tools.ToDegrees = function (angle) {
  8642. return angle * 180 / Math.PI;
  8643. };
  8644. Tools.ToRadians = function (angle) {
  8645. return angle * Math.PI / 180;
  8646. };
  8647. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8648. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8649. var output = "";
  8650. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8651. var i = 0;
  8652. var bytes = new Uint8Array(buffer);
  8653. while (i < bytes.length) {
  8654. chr1 = bytes[i++];
  8655. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8656. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8657. enc1 = chr1 >> 2;
  8658. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8659. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8660. enc4 = chr3 & 63;
  8661. if (isNaN(chr2)) {
  8662. enc3 = enc4 = 64;
  8663. }
  8664. else if (isNaN(chr3)) {
  8665. enc4 = 64;
  8666. }
  8667. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8668. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8669. }
  8670. return "data:image/png;base64," + output;
  8671. };
  8672. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8673. if (bias === void 0) { bias = null; }
  8674. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8675. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8676. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8677. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8678. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8679. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8680. }
  8681. if (bias) {
  8682. minimum.x -= minimum.x * bias.x + bias.y;
  8683. minimum.y -= minimum.y * bias.x + bias.y;
  8684. minimum.z -= minimum.z * bias.x + bias.y;
  8685. maximum.x += maximum.x * bias.x + bias.y;
  8686. maximum.y += maximum.y * bias.x + bias.y;
  8687. maximum.z += maximum.z * bias.x + bias.y;
  8688. }
  8689. return {
  8690. minimum: minimum,
  8691. maximum: maximum
  8692. };
  8693. };
  8694. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8695. if (bias === void 0) { bias = null; }
  8696. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8697. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8698. if (!stride) {
  8699. stride = 3;
  8700. }
  8701. for (var index = start; index < start + count; index++) {
  8702. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8703. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8704. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8705. }
  8706. if (bias) {
  8707. minimum.x -= minimum.x * bias.x + bias.y;
  8708. minimum.y -= minimum.y * bias.x + bias.y;
  8709. minimum.z -= minimum.z * bias.x + bias.y;
  8710. maximum.x += maximum.x * bias.x + bias.y;
  8711. maximum.y += maximum.y * bias.x + bias.y;
  8712. maximum.z += maximum.z * bias.x + bias.y;
  8713. }
  8714. return {
  8715. minimum: minimum,
  8716. maximum: maximum
  8717. };
  8718. };
  8719. Tools.Vector2ArrayFeeder = function (array) {
  8720. return function (index) {
  8721. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8722. var length = isFloatArray ? array.length / 2 : array.length;
  8723. if (index >= length) {
  8724. return null;
  8725. }
  8726. if (isFloatArray) {
  8727. var fa = array;
  8728. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8729. }
  8730. var a = array;
  8731. return a[index];
  8732. };
  8733. };
  8734. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8735. if (bias === void 0) { bias = null; }
  8736. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8737. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8738. var i = 0;
  8739. var cur = feeder(i++);
  8740. while (cur) {
  8741. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8742. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8743. cur = feeder(i++);
  8744. }
  8745. if (bias) {
  8746. minimum.x -= minimum.x * bias.x + bias.y;
  8747. minimum.y -= minimum.y * bias.x + bias.y;
  8748. maximum.x += maximum.x * bias.x + bias.y;
  8749. maximum.y += maximum.y * bias.x + bias.y;
  8750. }
  8751. return {
  8752. minimum: minimum,
  8753. maximum: maximum
  8754. };
  8755. };
  8756. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8757. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8758. return null;
  8759. return Array.isArray(obj) ? obj : [obj];
  8760. };
  8761. // Misc.
  8762. Tools.GetPointerPrefix = function () {
  8763. var eventPrefix = "pointer";
  8764. // Check if pointer events are supported
  8765. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8766. eventPrefix = "mouse";
  8767. }
  8768. return eventPrefix;
  8769. };
  8770. /**
  8771. * @param func - the function to be called
  8772. * @param requester - the object that will request the next frame. Falls back to window.
  8773. */
  8774. Tools.QueueNewFrame = function (func, requester) {
  8775. if (!Tools.IsWindowObjectExist()) {
  8776. return setTimeout(func, 16);
  8777. }
  8778. if (!requester) {
  8779. requester = window;
  8780. }
  8781. if (requester.requestAnimationFrame) {
  8782. return requester.requestAnimationFrame(func);
  8783. }
  8784. else if (requester.msRequestAnimationFrame) {
  8785. return requester.msRequestAnimationFrame(func);
  8786. }
  8787. else if (requester.webkitRequestAnimationFrame) {
  8788. return requester.webkitRequestAnimationFrame(func);
  8789. }
  8790. else if (requester.mozRequestAnimationFrame) {
  8791. return requester.mozRequestAnimationFrame(func);
  8792. }
  8793. else if (requester.oRequestAnimationFrame) {
  8794. return requester.oRequestAnimationFrame(func);
  8795. }
  8796. else {
  8797. return window.setTimeout(func, 16);
  8798. }
  8799. };
  8800. Tools.RequestFullscreen = function (element) {
  8801. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8802. if (!requestFunction)
  8803. return;
  8804. requestFunction.call(element);
  8805. };
  8806. Tools.ExitFullscreen = function () {
  8807. if (document.exitFullscreen) {
  8808. document.exitFullscreen();
  8809. }
  8810. else if (document.mozCancelFullScreen) {
  8811. document.mozCancelFullScreen();
  8812. }
  8813. else if (document.webkitCancelFullScreen) {
  8814. document.webkitCancelFullScreen();
  8815. }
  8816. else if (document.msCancelFullScreen) {
  8817. document.msCancelFullScreen();
  8818. }
  8819. };
  8820. Tools.SetCorsBehavior = function (url, element) {
  8821. if (url && url.indexOf("data:") === 0) {
  8822. return;
  8823. }
  8824. if (Tools.CorsBehavior) {
  8825. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8826. element.crossOrigin = Tools.CorsBehavior;
  8827. }
  8828. else {
  8829. var result = Tools.CorsBehavior(url);
  8830. if (result) {
  8831. element.crossOrigin = result;
  8832. }
  8833. }
  8834. }
  8835. };
  8836. // External files
  8837. Tools.CleanUrl = function (url) {
  8838. url = url.replace(/#/mg, "%23");
  8839. return url;
  8840. };
  8841. Tools.LoadImage = function (url, onLoad, onError, database) {
  8842. if (url instanceof ArrayBuffer) {
  8843. url = Tools.EncodeArrayBufferTobase64(url);
  8844. }
  8845. url = Tools.CleanUrl(url);
  8846. url = Tools.PreprocessUrl(url);
  8847. var img = new Image();
  8848. Tools.SetCorsBehavior(url, img);
  8849. var loadHandler = function () {
  8850. img.removeEventListener("load", loadHandler);
  8851. img.removeEventListener("error", errorHandler);
  8852. onLoad(img);
  8853. };
  8854. var errorHandler = function (err) {
  8855. img.removeEventListener("load", loadHandler);
  8856. img.removeEventListener("error", errorHandler);
  8857. Tools.Error("Error while trying to load image: " + url);
  8858. if (onError) {
  8859. onError("Error while trying to load image: " + url, err);
  8860. }
  8861. };
  8862. img.addEventListener("load", loadHandler);
  8863. img.addEventListener("error", errorHandler);
  8864. var noIndexedDB = function () {
  8865. img.src = url;
  8866. };
  8867. var loadFromIndexedDB = function () {
  8868. if (database) {
  8869. database.loadImageFromDB(url, img);
  8870. }
  8871. };
  8872. //ANY database to do!
  8873. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8874. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8875. }
  8876. else {
  8877. if (url.indexOf("file:") !== -1) {
  8878. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8879. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8880. try {
  8881. var blobURL;
  8882. try {
  8883. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8884. }
  8885. catch (ex) {
  8886. // Chrome doesn't support oneTimeOnly parameter
  8887. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8888. }
  8889. img.src = blobURL;
  8890. }
  8891. catch (e) {
  8892. img.src = "";
  8893. }
  8894. return img;
  8895. }
  8896. }
  8897. noIndexedDB();
  8898. }
  8899. return img;
  8900. };
  8901. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8902. url = Tools.CleanUrl(url);
  8903. url = Tools.PreprocessUrl(url);
  8904. // If file and file input are set
  8905. if (url.indexOf("file:") !== -1) {
  8906. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8907. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8908. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8909. }
  8910. }
  8911. var loadUrl = Tools.BaseUrl + url;
  8912. var aborted = false;
  8913. var fileRequest = {
  8914. onCompleteObservable: new BABYLON.Observable(),
  8915. abort: function () { return aborted = true; },
  8916. };
  8917. var requestFile = function () {
  8918. var request = new XMLHttpRequest();
  8919. var retryHandle = null;
  8920. fileRequest.abort = function () {
  8921. aborted = true;
  8922. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8923. request.abort();
  8924. }
  8925. if (retryHandle !== null) {
  8926. clearTimeout(retryHandle);
  8927. retryHandle = null;
  8928. }
  8929. };
  8930. var retryLoop = function (retryIndex) {
  8931. request.open('GET', loadUrl, true);
  8932. if (useArrayBuffer) {
  8933. request.responseType = "arraybuffer";
  8934. }
  8935. if (onProgress) {
  8936. request.addEventListener("progress", onProgress);
  8937. }
  8938. var onLoadEnd = function () {
  8939. request.removeEventListener("loadend", onLoadEnd);
  8940. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8941. fileRequest.onCompleteObservable.clear();
  8942. };
  8943. request.addEventListener("loadend", onLoadEnd);
  8944. var onReadyStateChange = function () {
  8945. if (aborted) {
  8946. return;
  8947. }
  8948. // In case of undefined state in some browsers.
  8949. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8950. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8951. request.removeEventListener("readystatechange", onReadyStateChange);
  8952. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8953. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8954. return;
  8955. }
  8956. var retryStrategy = Tools.DefaultRetryStrategy;
  8957. if (retryStrategy) {
  8958. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8959. if (waitTime !== -1) {
  8960. // Prevent the request from completing for retry.
  8961. request.removeEventListener("loadend", onLoadEnd);
  8962. request = new XMLHttpRequest();
  8963. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8964. return;
  8965. }
  8966. }
  8967. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8968. if (onError) {
  8969. onError(request, e);
  8970. }
  8971. else {
  8972. throw e;
  8973. }
  8974. }
  8975. };
  8976. request.addEventListener("readystatechange", onReadyStateChange);
  8977. request.send();
  8978. };
  8979. retryLoop(0);
  8980. };
  8981. // Caching all files
  8982. if (database && database.enableSceneOffline) {
  8983. var noIndexedDB_1 = function () {
  8984. if (!aborted) {
  8985. requestFile();
  8986. }
  8987. };
  8988. var loadFromIndexedDB = function () {
  8989. // TODO: database needs to support aborting and should return a IFileRequest
  8990. if (aborted) {
  8991. return;
  8992. }
  8993. if (database) {
  8994. database.loadFileFromDB(url, function (data) {
  8995. if (!aborted) {
  8996. onSuccess(data);
  8997. }
  8998. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8999. }, onProgress ? function (event) {
  9000. if (!aborted) {
  9001. onProgress(event);
  9002. }
  9003. } : undefined, noIndexedDB_1, useArrayBuffer);
  9004. }
  9005. };
  9006. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9007. }
  9008. else {
  9009. requestFile();
  9010. }
  9011. return fileRequest;
  9012. };
  9013. /**
  9014. * Load a script (identified by an url). When the url returns, the
  9015. * content of this file is added into a new script element, attached to the DOM (body element)
  9016. */
  9017. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9018. var head = document.getElementsByTagName('head')[0];
  9019. var script = document.createElement('script');
  9020. script.type = 'text/javascript';
  9021. script.src = scriptUrl;
  9022. script.onload = function () {
  9023. if (onSuccess) {
  9024. onSuccess();
  9025. }
  9026. };
  9027. script.onerror = function (e) {
  9028. if (onError) {
  9029. onError("Unable to load script '" + scriptUrl + "'", e);
  9030. }
  9031. };
  9032. head.appendChild(script);
  9033. };
  9034. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9035. var reader = new FileReader();
  9036. var request = {
  9037. onCompleteObservable: new BABYLON.Observable(),
  9038. abort: function () { return reader.abort(); },
  9039. };
  9040. reader.onloadend = function (e) {
  9041. request.onCompleteObservable.notifyObservers(request);
  9042. };
  9043. reader.onload = function (e) {
  9044. //target doesn't have result from ts 1.3
  9045. callback(e.target['result']);
  9046. };
  9047. reader.onprogress = progressCallback;
  9048. reader.readAsDataURL(fileToLoad);
  9049. return request;
  9050. };
  9051. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9052. var reader = new FileReader();
  9053. var request = {
  9054. onCompleteObservable: new BABYLON.Observable(),
  9055. abort: function () { return reader.abort(); },
  9056. };
  9057. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9058. reader.onerror = function (e) {
  9059. Tools.Log("Error while reading file: " + fileToLoad.name);
  9060. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9061. };
  9062. reader.onload = function (e) {
  9063. //target doesn't have result from ts 1.3
  9064. callback(e.target['result']);
  9065. };
  9066. if (progressCallBack) {
  9067. reader.onprogress = progressCallBack;
  9068. }
  9069. if (!useArrayBuffer) {
  9070. // Asynchronous read
  9071. reader.readAsText(fileToLoad);
  9072. }
  9073. else {
  9074. reader.readAsArrayBuffer(fileToLoad);
  9075. }
  9076. return request;
  9077. };
  9078. //returns a downloadable url to a file content.
  9079. Tools.FileAsURL = function (content) {
  9080. var fileBlob = new Blob([content]);
  9081. var url = window.URL || window.webkitURL;
  9082. var link = url.createObjectURL(fileBlob);
  9083. return link;
  9084. };
  9085. // Misc.
  9086. Tools.Format = function (value, decimals) {
  9087. if (decimals === void 0) { decimals = 2; }
  9088. return value.toFixed(decimals);
  9089. };
  9090. Tools.CheckExtends = function (v, min, max) {
  9091. if (v.x < min.x)
  9092. min.x = v.x;
  9093. if (v.y < min.y)
  9094. min.y = v.y;
  9095. if (v.z < min.z)
  9096. min.z = v.z;
  9097. if (v.x > max.x)
  9098. max.x = v.x;
  9099. if (v.y > max.y)
  9100. max.y = v.y;
  9101. if (v.z > max.z)
  9102. max.z = v.z;
  9103. };
  9104. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9105. for (var prop in source) {
  9106. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9107. continue;
  9108. }
  9109. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9110. continue;
  9111. }
  9112. var sourceValue = source[prop];
  9113. var typeOfSourceValue = typeof sourceValue;
  9114. if (typeOfSourceValue === "function") {
  9115. continue;
  9116. }
  9117. try {
  9118. if (typeOfSourceValue === "object") {
  9119. if (sourceValue instanceof Array) {
  9120. destination[prop] = [];
  9121. if (sourceValue.length > 0) {
  9122. if (typeof sourceValue[0] == "object") {
  9123. for (var index = 0; index < sourceValue.length; index++) {
  9124. var clonedValue = cloneValue(sourceValue[index], destination);
  9125. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9126. destination[prop].push(clonedValue);
  9127. }
  9128. }
  9129. }
  9130. else {
  9131. destination[prop] = sourceValue.slice(0);
  9132. }
  9133. }
  9134. }
  9135. else {
  9136. destination[prop] = cloneValue(sourceValue, destination);
  9137. }
  9138. }
  9139. else {
  9140. destination[prop] = sourceValue;
  9141. }
  9142. }
  9143. catch (e) {
  9144. // Just ignore error (it could be because of a read-only property)
  9145. }
  9146. }
  9147. };
  9148. Tools.IsEmpty = function (obj) {
  9149. for (var i in obj) {
  9150. if (obj.hasOwnProperty(i)) {
  9151. return false;
  9152. }
  9153. }
  9154. return true;
  9155. };
  9156. Tools.RegisterTopRootEvents = function (events) {
  9157. for (var index = 0; index < events.length; index++) {
  9158. var event = events[index];
  9159. window.addEventListener(event.name, event.handler, false);
  9160. try {
  9161. if (window.parent) {
  9162. window.parent.addEventListener(event.name, event.handler, false);
  9163. }
  9164. }
  9165. catch (e) {
  9166. // Silently fails...
  9167. }
  9168. }
  9169. };
  9170. Tools.UnregisterTopRootEvents = function (events) {
  9171. for (var index = 0; index < events.length; index++) {
  9172. var event = events[index];
  9173. window.removeEventListener(event.name, event.handler);
  9174. try {
  9175. if (window.parent) {
  9176. window.parent.removeEventListener(event.name, event.handler);
  9177. }
  9178. }
  9179. catch (e) {
  9180. // Silently fails...
  9181. }
  9182. }
  9183. };
  9184. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9185. if (mimeType === void 0) { mimeType = "image/png"; }
  9186. // Read the contents of the framebuffer
  9187. var numberOfChannelsByLine = width * 4;
  9188. var halfHeight = height / 2;
  9189. //Reading datas from WebGL
  9190. var data = engine.readPixels(0, 0, width, height);
  9191. //To flip image on Y axis.
  9192. for (var i = 0; i < halfHeight; i++) {
  9193. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9194. var currentCell = j + i * numberOfChannelsByLine;
  9195. var targetLine = height - i - 1;
  9196. var targetCell = j + targetLine * numberOfChannelsByLine;
  9197. var temp = data[currentCell];
  9198. data[currentCell] = data[targetCell];
  9199. data[targetCell] = temp;
  9200. }
  9201. }
  9202. // Create a 2D canvas to store the result
  9203. if (!screenshotCanvas) {
  9204. screenshotCanvas = document.createElement('canvas');
  9205. }
  9206. screenshotCanvas.width = width;
  9207. screenshotCanvas.height = height;
  9208. var context = screenshotCanvas.getContext('2d');
  9209. if (context) {
  9210. // Copy the pixels to a 2D canvas
  9211. var imageData = context.createImageData(width, height);
  9212. var castData = (imageData.data);
  9213. castData.set(data);
  9214. context.putImageData(imageData, 0, 0);
  9215. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9216. }
  9217. };
  9218. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9219. if (mimeType === void 0) { mimeType = "image/png"; }
  9220. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9221. if (successCallback) {
  9222. successCallback(base64Image);
  9223. }
  9224. else {
  9225. // We need HTMLCanvasElement.toBlob for HD screenshots
  9226. if (!screenshotCanvas.toBlob) {
  9227. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9228. screenshotCanvas.toBlob = function (callback, type, quality) {
  9229. var _this = this;
  9230. setTimeout(function () {
  9231. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9232. for (var i = 0; i < len; i++) {
  9233. arr[i] = binStr.charCodeAt(i);
  9234. }
  9235. callback(new Blob([arr], { type: type || 'image/png' }));
  9236. });
  9237. };
  9238. }
  9239. screenshotCanvas.toBlob(function (blob) {
  9240. var url = URL.createObjectURL(blob);
  9241. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9242. if (("download" in document.createElement("a"))) {
  9243. var a = window.document.createElement("a");
  9244. a.href = url;
  9245. if (fileName) {
  9246. a.setAttribute("download", fileName);
  9247. }
  9248. else {
  9249. var date = new Date();
  9250. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9251. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9252. }
  9253. window.document.body.appendChild(a);
  9254. a.addEventListener("click", function () {
  9255. if (a.parentElement) {
  9256. a.parentElement.removeChild(a);
  9257. }
  9258. });
  9259. a.click();
  9260. }
  9261. else {
  9262. var newWindow = window.open("");
  9263. if (!newWindow)
  9264. return;
  9265. var img = newWindow.document.createElement("img");
  9266. img.onload = function () {
  9267. // no longer need to read the blob so it's revoked
  9268. URL.revokeObjectURL(url);
  9269. };
  9270. img.src = url;
  9271. newWindow.document.body.appendChild(img);
  9272. }
  9273. });
  9274. }
  9275. };
  9276. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9277. if (mimeType === void 0) { mimeType = "image/png"; }
  9278. var width;
  9279. var height;
  9280. // If a precision value is specified
  9281. if (size.precision) {
  9282. width = Math.round(engine.getRenderWidth() * size.precision);
  9283. height = Math.round(width / engine.getAspectRatio(camera));
  9284. }
  9285. else if (size.width && size.height) {
  9286. width = size.width;
  9287. height = size.height;
  9288. }
  9289. //If passing only width, computing height to keep display canvas ratio.
  9290. else if (size.width && !size.height) {
  9291. width = size.width;
  9292. height = Math.round(width / engine.getAspectRatio(camera));
  9293. }
  9294. //If passing only height, computing width to keep display canvas ratio.
  9295. else if (size.height && !size.width) {
  9296. height = size.height;
  9297. width = Math.round(height * engine.getAspectRatio(camera));
  9298. }
  9299. //Assuming here that "size" parameter is a number
  9300. else if (!isNaN(size)) {
  9301. height = size;
  9302. width = size;
  9303. }
  9304. else {
  9305. Tools.Error("Invalid 'size' parameter !");
  9306. return;
  9307. }
  9308. if (!screenshotCanvas) {
  9309. screenshotCanvas = document.createElement('canvas');
  9310. }
  9311. screenshotCanvas.width = width;
  9312. screenshotCanvas.height = height;
  9313. var renderContext = screenshotCanvas.getContext("2d");
  9314. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9315. var newWidth = width;
  9316. var newHeight = newWidth / ratio;
  9317. if (newHeight > height) {
  9318. newHeight = height;
  9319. newWidth = newHeight * ratio;
  9320. }
  9321. var offsetX = Math.max(0, width - newWidth) / 2;
  9322. var offsetY = Math.max(0, height - newHeight) / 2;
  9323. var renderingCanvas = engine.getRenderingCanvas();
  9324. if (renderContext && renderingCanvas) {
  9325. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9326. }
  9327. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9328. };
  9329. /**
  9330. * Generates an image screenshot from the specified camera.
  9331. *
  9332. * @param engine The engine to use for rendering
  9333. * @param camera The camera to use for rendering
  9334. * @param size This parameter can be set to a single number or to an object with the
  9335. * following (optional) properties: precision, width, height. If a single number is passed,
  9336. * it will be used for both width and height. If an object is passed, the screenshot size
  9337. * will be derived from the parameters. The precision property is a multiplier allowing
  9338. * rendering at a higher or lower resolution.
  9339. * @param successCallback The callback receives a single parameter which contains the
  9340. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9341. * src parameter of an <img> to display it.
  9342. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9343. * Check your browser for supported MIME types.
  9344. * @param samples Texture samples (default: 1)
  9345. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9346. * @param fileName A name for for the downloaded file.
  9347. * @constructor
  9348. */
  9349. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9350. if (mimeType === void 0) { mimeType = "image/png"; }
  9351. if (samples === void 0) { samples = 1; }
  9352. if (antialiasing === void 0) { antialiasing = false; }
  9353. var width;
  9354. var height;
  9355. //If a precision value is specified
  9356. if (size.precision) {
  9357. width = Math.round(engine.getRenderWidth() * size.precision);
  9358. height = Math.round(width / engine.getAspectRatio(camera));
  9359. size = { width: width, height: height };
  9360. }
  9361. else if (size.width && size.height) {
  9362. width = size.width;
  9363. height = size.height;
  9364. }
  9365. //If passing only width, computing height to keep display canvas ratio.
  9366. else if (size.width && !size.height) {
  9367. width = size.width;
  9368. height = Math.round(width / engine.getAspectRatio(camera));
  9369. size = { width: width, height: height };
  9370. }
  9371. //If passing only height, computing width to keep display canvas ratio.
  9372. else if (size.height && !size.width) {
  9373. height = size.height;
  9374. width = Math.round(height * engine.getAspectRatio(camera));
  9375. size = { width: width, height: height };
  9376. }
  9377. //Assuming here that "size" parameter is a number
  9378. else if (!isNaN(size)) {
  9379. height = size;
  9380. width = size;
  9381. }
  9382. else {
  9383. Tools.Error("Invalid 'size' parameter !");
  9384. return;
  9385. }
  9386. var scene = camera.getScene();
  9387. var previousCamera = null;
  9388. if (scene.activeCamera !== camera) {
  9389. previousCamera = scene.activeCamera;
  9390. scene.activeCamera = camera;
  9391. }
  9392. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9393. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9394. texture.renderList = null;
  9395. texture.samples = samples;
  9396. if (antialiasing) {
  9397. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9398. }
  9399. texture.onAfterRenderObservable.add(function () {
  9400. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9401. });
  9402. scene.incrementRenderId();
  9403. scene.resetCachedMaterial();
  9404. texture.render(true);
  9405. texture.dispose();
  9406. if (previousCamera) {
  9407. scene.activeCamera = previousCamera;
  9408. }
  9409. camera.getProjectionMatrix(true); // Force cache refresh;
  9410. };
  9411. // XHR response validator for local file scenario
  9412. Tools.ValidateXHRData = function (xhr, dataType) {
  9413. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9414. if (dataType === void 0) { dataType = 7; }
  9415. try {
  9416. if (dataType & 1) {
  9417. if (xhr.responseText && xhr.responseText.length > 0) {
  9418. return true;
  9419. }
  9420. else if (dataType === 1) {
  9421. return false;
  9422. }
  9423. }
  9424. if (dataType & 2) {
  9425. // Check header width and height since there is no "TGA" magic number
  9426. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9427. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9428. return true;
  9429. }
  9430. else if (dataType === 2) {
  9431. return false;
  9432. }
  9433. }
  9434. if (dataType & 4) {
  9435. // Check for the "DDS" magic number
  9436. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9437. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9438. return true;
  9439. }
  9440. else {
  9441. return false;
  9442. }
  9443. }
  9444. }
  9445. catch (e) {
  9446. // Global protection
  9447. }
  9448. return false;
  9449. };
  9450. /**
  9451. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9452. * Be aware Math.random() could cause collisions, but:
  9453. * "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"
  9454. */
  9455. Tools.RandomId = function () {
  9456. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9457. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9458. return v.toString(16);
  9459. });
  9460. };
  9461. /**
  9462. * Test if the given uri is a base64 string.
  9463. * @param uri The uri to test
  9464. * @return True if the uri is a base64 string or false otherwise.
  9465. */
  9466. Tools.IsBase64 = function (uri) {
  9467. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9468. };
  9469. /**
  9470. * Decode the given base64 uri.
  9471. * @param uri The uri to decode
  9472. * @return The decoded base64 data.
  9473. */
  9474. Tools.DecodeBase64 = function (uri) {
  9475. var decodedString = atob(uri.split(",")[1]);
  9476. var bufferLength = decodedString.length;
  9477. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9478. for (var i = 0; i < bufferLength; i++) {
  9479. bufferView[i] = decodedString.charCodeAt(i);
  9480. }
  9481. return bufferView.buffer;
  9482. };
  9483. Object.defineProperty(Tools, "NoneLogLevel", {
  9484. get: function () {
  9485. return Tools._NoneLogLevel;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Object.defineProperty(Tools, "MessageLogLevel", {
  9491. get: function () {
  9492. return Tools._MessageLogLevel;
  9493. },
  9494. enumerable: true,
  9495. configurable: true
  9496. });
  9497. Object.defineProperty(Tools, "WarningLogLevel", {
  9498. get: function () {
  9499. return Tools._WarningLogLevel;
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. Object.defineProperty(Tools, "ErrorLogLevel", {
  9505. get: function () {
  9506. return Tools._ErrorLogLevel;
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(Tools, "AllLogLevel", {
  9512. get: function () {
  9513. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9514. },
  9515. enumerable: true,
  9516. configurable: true
  9517. });
  9518. Tools._AddLogEntry = function (entry) {
  9519. Tools._LogCache = entry + Tools._LogCache;
  9520. if (Tools.OnNewCacheEntry) {
  9521. Tools.OnNewCacheEntry(entry);
  9522. }
  9523. };
  9524. Tools._FormatMessage = function (message) {
  9525. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9526. var date = new Date();
  9527. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9528. };
  9529. Tools._LogDisabled = function (message) {
  9530. // nothing to do
  9531. };
  9532. Tools._LogEnabled = function (message) {
  9533. var formattedMessage = Tools._FormatMessage(message);
  9534. console.log("BJS - " + formattedMessage);
  9535. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9536. Tools._AddLogEntry(entry);
  9537. };
  9538. Tools._WarnDisabled = function (message) {
  9539. // nothing to do
  9540. };
  9541. Tools._WarnEnabled = function (message) {
  9542. var formattedMessage = Tools._FormatMessage(message);
  9543. console.warn("BJS - " + formattedMessage);
  9544. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9545. Tools._AddLogEntry(entry);
  9546. };
  9547. Tools._ErrorDisabled = function (message) {
  9548. // nothing to do
  9549. };
  9550. Tools._ErrorEnabled = function (message) {
  9551. Tools.errorsCount++;
  9552. var formattedMessage = Tools._FormatMessage(message);
  9553. console.error("BJS - " + formattedMessage);
  9554. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9555. Tools._AddLogEntry(entry);
  9556. };
  9557. Object.defineProperty(Tools, "LogCache", {
  9558. get: function () {
  9559. return Tools._LogCache;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Tools.ClearLogCache = function () {
  9565. Tools._LogCache = "";
  9566. Tools.errorsCount = 0;
  9567. };
  9568. Object.defineProperty(Tools, "LogLevels", {
  9569. set: function (level) {
  9570. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9571. Tools.Log = Tools._LogEnabled;
  9572. }
  9573. else {
  9574. Tools.Log = Tools._LogDisabled;
  9575. }
  9576. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9577. Tools.Warn = Tools._WarnEnabled;
  9578. }
  9579. else {
  9580. Tools.Warn = Tools._WarnDisabled;
  9581. }
  9582. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9583. Tools.Error = Tools._ErrorEnabled;
  9584. }
  9585. else {
  9586. Tools.Error = Tools._ErrorDisabled;
  9587. }
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Tools.IsWindowObjectExist = function () {
  9593. return (typeof window) !== "undefined";
  9594. };
  9595. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9596. get: function () {
  9597. return Tools._PerformanceNoneLogLevel;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9603. get: function () {
  9604. return Tools._PerformanceUserMarkLogLevel;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9610. get: function () {
  9611. return Tools._PerformanceConsoleLogLevel;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9617. set: function (level) {
  9618. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9619. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9620. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9621. return;
  9622. }
  9623. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9624. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9625. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9626. return;
  9627. }
  9628. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9629. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9630. },
  9631. enumerable: true,
  9632. configurable: true
  9633. });
  9634. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9635. };
  9636. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9637. };
  9638. Tools._StartUserMark = function (counterName, condition) {
  9639. if (condition === void 0) { condition = true; }
  9640. if (!Tools._performance) {
  9641. if (!Tools.IsWindowObjectExist()) {
  9642. return;
  9643. }
  9644. Tools._performance = window.performance;
  9645. }
  9646. if (!condition || !Tools._performance.mark) {
  9647. return;
  9648. }
  9649. Tools._performance.mark(counterName + "-Begin");
  9650. };
  9651. Tools._EndUserMark = function (counterName, condition) {
  9652. if (condition === void 0) { condition = true; }
  9653. if (!condition || !Tools._performance.mark) {
  9654. return;
  9655. }
  9656. Tools._performance.mark(counterName + "-End");
  9657. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9658. };
  9659. Tools._StartPerformanceConsole = function (counterName, condition) {
  9660. if (condition === void 0) { condition = true; }
  9661. if (!condition) {
  9662. return;
  9663. }
  9664. Tools._StartUserMark(counterName, condition);
  9665. if (console.time) {
  9666. console.time(counterName);
  9667. }
  9668. };
  9669. Tools._EndPerformanceConsole = function (counterName, condition) {
  9670. if (condition === void 0) { condition = true; }
  9671. if (!condition) {
  9672. return;
  9673. }
  9674. Tools._EndUserMark(counterName, condition);
  9675. if (console.time) {
  9676. console.timeEnd(counterName);
  9677. }
  9678. };
  9679. Object.defineProperty(Tools, "Now", {
  9680. get: function () {
  9681. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9682. return window.performance.now();
  9683. }
  9684. return Date.now();
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. /**
  9690. * This method will return the name of the class used to create the instance of the given object.
  9691. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9692. * @param object the object to get the class name from
  9693. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9694. */
  9695. Tools.GetClassName = function (object, isType) {
  9696. if (isType === void 0) { isType = false; }
  9697. var name = null;
  9698. if (!isType && object.getClassName) {
  9699. name = object.getClassName();
  9700. }
  9701. else {
  9702. if (object instanceof Object) {
  9703. var classObj = isType ? object : Object.getPrototypeOf(object);
  9704. name = classObj.constructor["__bjsclassName__"];
  9705. }
  9706. if (!name) {
  9707. name = typeof object;
  9708. }
  9709. }
  9710. return name;
  9711. };
  9712. Tools.First = function (array, predicate) {
  9713. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9714. var el = array_1[_i];
  9715. if (predicate(el)) {
  9716. return el;
  9717. }
  9718. }
  9719. return null;
  9720. };
  9721. /**
  9722. * This method will return the name of the full name of the class, including its owning module (if any).
  9723. * 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).
  9724. * @param object the object to get the class name from
  9725. * @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.
  9726. */
  9727. Tools.getFullClassName = function (object, isType) {
  9728. if (isType === void 0) { isType = false; }
  9729. var className = null;
  9730. var moduleName = null;
  9731. if (!isType && object.getClassName) {
  9732. className = object.getClassName();
  9733. }
  9734. else {
  9735. if (object instanceof Object) {
  9736. var classObj = isType ? object : Object.getPrototypeOf(object);
  9737. className = classObj.constructor["__bjsclassName__"];
  9738. moduleName = classObj.constructor["__bjsmoduleName__"];
  9739. }
  9740. if (!className) {
  9741. className = typeof object;
  9742. }
  9743. }
  9744. if (!className) {
  9745. return null;
  9746. }
  9747. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9748. };
  9749. /**
  9750. * 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.
  9751. * @param array
  9752. */
  9753. Tools.arrayOrStringFeeder = function (array) {
  9754. return function (index) {
  9755. if (index >= array.length) {
  9756. return null;
  9757. }
  9758. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9759. if (val && val.getHashCode) {
  9760. val = val.getHashCode();
  9761. }
  9762. if (typeof val === "string") {
  9763. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9764. }
  9765. return val;
  9766. };
  9767. };
  9768. /**
  9769. * Compute the hashCode of a stream of number
  9770. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9771. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9772. * @return the hash code computed
  9773. */
  9774. Tools.hashCodeFromStream = function (feeder) {
  9775. // Based from here: http://stackoverflow.com/a/7616484/802124
  9776. var hash = 0;
  9777. var index = 0;
  9778. var chr = feeder(index++);
  9779. while (chr != null) {
  9780. hash = ((hash << 5) - hash) + chr;
  9781. hash |= 0; // Convert to 32bit integer
  9782. chr = feeder(index++);
  9783. }
  9784. return hash;
  9785. };
  9786. /**
  9787. * Returns a promise that resolves after the given amount of time.
  9788. * @param delay Number of milliseconds to delay
  9789. * @returns Promise that resolves after the given amount of time
  9790. */
  9791. Tools.DelayAsync = function (delay) {
  9792. return new Promise(function (resolve) {
  9793. setTimeout(function () {
  9794. resolve();
  9795. }, delay);
  9796. });
  9797. };
  9798. Tools.BaseUrl = "";
  9799. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9800. /**
  9801. * Default behaviour for cors in the application.
  9802. * It can be a string if the expected behavior is identical in the entire app.
  9803. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9804. */
  9805. Tools.CorsBehavior = "anonymous";
  9806. Tools.UseFallbackTexture = true;
  9807. /**
  9808. * Use this object to register external classes like custom textures or material
  9809. * to allow the laoders to instantiate them
  9810. */
  9811. Tools.RegisteredExternalClasses = {};
  9812. // Used in case of a texture loading problem
  9813. 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";
  9814. Tools._tmpFloatArray = new Float32Array(1);
  9815. Tools.PreprocessUrl = function (url) {
  9816. return url;
  9817. };
  9818. // Logs
  9819. Tools._NoneLogLevel = 0;
  9820. Tools._MessageLogLevel = 1;
  9821. Tools._WarningLogLevel = 2;
  9822. Tools._ErrorLogLevel = 4;
  9823. Tools._LogCache = "";
  9824. Tools.errorsCount = 0;
  9825. Tools.Log = Tools._LogEnabled;
  9826. Tools.Warn = Tools._WarnEnabled;
  9827. Tools.Error = Tools._ErrorEnabled;
  9828. // Performances
  9829. Tools._PerformanceNoneLogLevel = 0;
  9830. Tools._PerformanceUserMarkLogLevel = 1;
  9831. Tools._PerformanceConsoleLogLevel = 2;
  9832. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9833. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9834. return Tools;
  9835. }());
  9836. BABYLON.Tools = Tools;
  9837. /**
  9838. * This class is used to track a performance counter which is number based.
  9839. * The user has access to many properties which give statistics of different nature
  9840. *
  9841. * The implementer can track two kinds of Performance Counter: time and count
  9842. * 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.
  9843. * 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.
  9844. */
  9845. var PerfCounter = /** @class */ (function () {
  9846. function PerfCounter() {
  9847. this._startMonitoringTime = 0;
  9848. this._min = 0;
  9849. this._max = 0;
  9850. this._average = 0;
  9851. this._lastSecAverage = 0;
  9852. this._current = 0;
  9853. this._totalValueCount = 0;
  9854. this._totalAccumulated = 0;
  9855. this._lastSecAccumulated = 0;
  9856. this._lastSecTime = 0;
  9857. this._lastSecValueCount = 0;
  9858. }
  9859. Object.defineProperty(PerfCounter.prototype, "min", {
  9860. /**
  9861. * Returns the smallest value ever
  9862. */
  9863. get: function () {
  9864. return this._min;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(PerfCounter.prototype, "max", {
  9870. /**
  9871. * Returns the biggest value ever
  9872. */
  9873. get: function () {
  9874. return this._max;
  9875. },
  9876. enumerable: true,
  9877. configurable: true
  9878. });
  9879. Object.defineProperty(PerfCounter.prototype, "average", {
  9880. /**
  9881. * Returns the average value since the performance counter is running
  9882. */
  9883. get: function () {
  9884. return this._average;
  9885. },
  9886. enumerable: true,
  9887. configurable: true
  9888. });
  9889. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9890. /**
  9891. * Returns the average value of the last second the counter was monitored
  9892. */
  9893. get: function () {
  9894. return this._lastSecAverage;
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. Object.defineProperty(PerfCounter.prototype, "current", {
  9900. /**
  9901. * Returns the current value
  9902. */
  9903. get: function () {
  9904. return this._current;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(PerfCounter.prototype, "total", {
  9910. get: function () {
  9911. return this._totalAccumulated;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(PerfCounter.prototype, "count", {
  9917. get: function () {
  9918. return this._totalValueCount;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. /**
  9924. * Call this method to start monitoring a new frame.
  9925. * 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.
  9926. */
  9927. PerfCounter.prototype.fetchNewFrame = function () {
  9928. this._totalValueCount++;
  9929. this._current = 0;
  9930. this._lastSecValueCount++;
  9931. };
  9932. /**
  9933. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9934. * @param newCount the count value to add to the monitored count
  9935. * @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.
  9936. */
  9937. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9938. if (!PerfCounter.Enabled) {
  9939. return;
  9940. }
  9941. this._current += newCount;
  9942. if (fetchResult) {
  9943. this._fetchResult();
  9944. }
  9945. };
  9946. /**
  9947. * Start monitoring this performance counter
  9948. */
  9949. PerfCounter.prototype.beginMonitoring = function () {
  9950. if (!PerfCounter.Enabled) {
  9951. return;
  9952. }
  9953. this._startMonitoringTime = Tools.Now;
  9954. };
  9955. /**
  9956. * Compute the time lapsed since the previous beginMonitoring() call.
  9957. * @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
  9958. */
  9959. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9960. if (newFrame === void 0) { newFrame = true; }
  9961. if (!PerfCounter.Enabled) {
  9962. return;
  9963. }
  9964. if (newFrame) {
  9965. this.fetchNewFrame();
  9966. }
  9967. var currentTime = Tools.Now;
  9968. this._current = currentTime - this._startMonitoringTime;
  9969. if (newFrame) {
  9970. this._fetchResult();
  9971. }
  9972. };
  9973. PerfCounter.prototype._fetchResult = function () {
  9974. this._totalAccumulated += this._current;
  9975. this._lastSecAccumulated += this._current;
  9976. // Min/Max update
  9977. this._min = Math.min(this._min, this._current);
  9978. this._max = Math.max(this._max, this._current);
  9979. this._average = this._totalAccumulated / this._totalValueCount;
  9980. // Reset last sec?
  9981. var now = Tools.Now;
  9982. if ((now - this._lastSecTime) > 1000) {
  9983. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9984. this._lastSecTime = now;
  9985. this._lastSecAccumulated = 0;
  9986. this._lastSecValueCount = 0;
  9987. }
  9988. };
  9989. PerfCounter.Enabled = true;
  9990. return PerfCounter;
  9991. }());
  9992. BABYLON.PerfCounter = PerfCounter;
  9993. /**
  9994. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9995. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9996. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9997. * @param name The name of the class, case should be preserved
  9998. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9999. */
  10000. function className(name, module) {
  10001. return function (target) {
  10002. target["__bjsclassName__"] = name;
  10003. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10004. };
  10005. }
  10006. BABYLON.className = className;
  10007. /**
  10008. * An implementation of a loop for asynchronous functions.
  10009. */
  10010. var AsyncLoop = /** @class */ (function () {
  10011. /**
  10012. * Constroctor.
  10013. * @param iterations the number of iterations.
  10014. * @param _fn the function to run each iteration
  10015. * @param _successCallback the callback that will be called upon succesful execution
  10016. * @param offset starting offset.
  10017. */
  10018. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10019. if (offset === void 0) { offset = 0; }
  10020. this.iterations = iterations;
  10021. this._fn = _fn;
  10022. this._successCallback = _successCallback;
  10023. this.index = offset - 1;
  10024. this._done = false;
  10025. }
  10026. /**
  10027. * Execute the next iteration. Must be called after the last iteration was finished.
  10028. */
  10029. AsyncLoop.prototype.executeNext = function () {
  10030. if (!this._done) {
  10031. if (this.index + 1 < this.iterations) {
  10032. ++this.index;
  10033. this._fn(this);
  10034. }
  10035. else {
  10036. this.breakLoop();
  10037. }
  10038. }
  10039. };
  10040. /**
  10041. * Break the loop and run the success callback.
  10042. */
  10043. AsyncLoop.prototype.breakLoop = function () {
  10044. this._done = true;
  10045. this._successCallback();
  10046. };
  10047. /**
  10048. * Helper function
  10049. */
  10050. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10051. if (offset === void 0) { offset = 0; }
  10052. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10053. loop.executeNext();
  10054. return loop;
  10055. };
  10056. /**
  10057. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10058. * @param iterations total number of iterations
  10059. * @param syncedIterations number of synchronous iterations in each async iteration.
  10060. * @param fn the function to call each iteration.
  10061. * @param callback a success call back that will be called when iterating stops.
  10062. * @param breakFunction a break condition (optional)
  10063. * @param timeout timeout settings for the setTimeout function. default - 0.
  10064. * @constructor
  10065. */
  10066. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10067. if (timeout === void 0) { timeout = 0; }
  10068. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10069. if (breakFunction && breakFunction())
  10070. loop.breakLoop();
  10071. else {
  10072. setTimeout(function () {
  10073. for (var i = 0; i < syncedIterations; ++i) {
  10074. var iteration = (loop.index * syncedIterations) + i;
  10075. if (iteration >= iterations)
  10076. break;
  10077. fn(iteration);
  10078. if (breakFunction && breakFunction()) {
  10079. loop.breakLoop();
  10080. break;
  10081. }
  10082. }
  10083. loop.executeNext();
  10084. }, timeout);
  10085. }
  10086. }, callback);
  10087. };
  10088. return AsyncLoop;
  10089. }());
  10090. BABYLON.AsyncLoop = AsyncLoop;
  10091. })(BABYLON || (BABYLON = {}));
  10092. //# sourceMappingURL=babylon.tools.js.map
  10093. var BABYLON;
  10094. (function (BABYLON) {
  10095. var PromiseStates;
  10096. (function (PromiseStates) {
  10097. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10098. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10099. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10100. })(PromiseStates || (PromiseStates = {}));
  10101. var FulFillmentAgregator = /** @class */ (function () {
  10102. function FulFillmentAgregator() {
  10103. this.count = 0;
  10104. this.target = 0;
  10105. this.results = [];
  10106. }
  10107. return FulFillmentAgregator;
  10108. }());
  10109. var InternalPromise = /** @class */ (function () {
  10110. function InternalPromise(resolver) {
  10111. var _this = this;
  10112. this._state = PromiseStates.Pending;
  10113. this._children = new Array();
  10114. this._rejectWasConsumed = false;
  10115. if (!resolver) {
  10116. return;
  10117. }
  10118. try {
  10119. resolver(function (value) {
  10120. _this._resolve(value);
  10121. }, function (reason) {
  10122. _this._reject(reason);
  10123. });
  10124. }
  10125. catch (e) {
  10126. this._reject(e);
  10127. }
  10128. }
  10129. Object.defineProperty(InternalPromise.prototype, "_result", {
  10130. get: function () {
  10131. return this._resultValue;
  10132. },
  10133. set: function (value) {
  10134. this._resultValue = value;
  10135. if (this._parent && this._parent._result === undefined) {
  10136. this._parent._result = value;
  10137. }
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. InternalPromise.prototype.catch = function (onRejected) {
  10143. return this.then(undefined, onRejected);
  10144. };
  10145. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10146. var _this = this;
  10147. var newPromise = new InternalPromise();
  10148. newPromise._onFulfilled = onFulfilled;
  10149. newPromise._onRejected = onRejected;
  10150. // Composition
  10151. this._children.push(newPromise);
  10152. newPromise._parent = this;
  10153. if (this._state !== PromiseStates.Pending) {
  10154. BABYLON.Tools.SetImmediate(function () {
  10155. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10156. var returnedValue = newPromise._resolve(_this._result);
  10157. if (returnedValue !== undefined && returnedValue !== null) {
  10158. if (returnedValue._state !== undefined) {
  10159. var returnedPromise = returnedValue;
  10160. newPromise._children.push(returnedPromise);
  10161. returnedPromise._parent = newPromise;
  10162. newPromise = returnedPromise;
  10163. }
  10164. else {
  10165. newPromise._result = returnedValue;
  10166. }
  10167. }
  10168. }
  10169. else {
  10170. newPromise._reject(_this._reason);
  10171. }
  10172. });
  10173. }
  10174. return newPromise;
  10175. };
  10176. InternalPromise.prototype._moveChildren = function (children) {
  10177. var _this = this;
  10178. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10179. this._children.forEach(function (child) {
  10180. child._parent = _this;
  10181. });
  10182. if (this._state === PromiseStates.Fulfilled) {
  10183. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10184. var child = _b[_i];
  10185. child._resolve(this._result);
  10186. }
  10187. }
  10188. else if (this._state === PromiseStates.Rejected) {
  10189. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10190. var child = _d[_c];
  10191. child._reject(this._reason);
  10192. }
  10193. }
  10194. var _a;
  10195. };
  10196. InternalPromise.prototype._resolve = function (value) {
  10197. try {
  10198. this._state = PromiseStates.Fulfilled;
  10199. var returnedValue = null;
  10200. if (this._onFulfilled) {
  10201. returnedValue = this._onFulfilled(value);
  10202. }
  10203. if (returnedValue !== undefined && returnedValue !== null) {
  10204. if (returnedValue._state !== undefined) {
  10205. // Transmit children
  10206. var returnedPromise = returnedValue;
  10207. returnedPromise._parent = this;
  10208. returnedPromise._moveChildren(this._children);
  10209. value = returnedPromise._result;
  10210. }
  10211. else {
  10212. value = returnedValue;
  10213. }
  10214. }
  10215. this._result = value;
  10216. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10217. var child = _a[_i];
  10218. child._resolve(value);
  10219. }
  10220. this._children.length = 0;
  10221. delete this._onFulfilled;
  10222. delete this._onRejected;
  10223. }
  10224. catch (e) {
  10225. this._reject(e, true);
  10226. }
  10227. };
  10228. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10229. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10230. this._state = PromiseStates.Rejected;
  10231. this._reason = reason;
  10232. if (this._onRejected && !onLocalThrow) {
  10233. try {
  10234. this._onRejected(reason);
  10235. this._rejectWasConsumed = true;
  10236. }
  10237. catch (e) {
  10238. reason = e;
  10239. }
  10240. }
  10241. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10242. var child = _a[_i];
  10243. if (this._rejectWasConsumed) {
  10244. child._resolve(null);
  10245. }
  10246. else {
  10247. child._reject(reason);
  10248. }
  10249. }
  10250. this._children.length = 0;
  10251. delete this._onFulfilled;
  10252. delete this._onRejected;
  10253. };
  10254. InternalPromise.resolve = function (value) {
  10255. var newPromise = new InternalPromise();
  10256. newPromise._resolve(value);
  10257. return newPromise;
  10258. };
  10259. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10260. promise.then(function (value) {
  10261. agregator.results[index] = value;
  10262. agregator.count++;
  10263. if (agregator.count === agregator.target) {
  10264. agregator.rootPromise._resolve(agregator.results);
  10265. }
  10266. return null;
  10267. }, function (reason) {
  10268. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10269. agregator.rootPromise._reject(reason);
  10270. }
  10271. });
  10272. };
  10273. InternalPromise.all = function (promises) {
  10274. var newPromise = new InternalPromise();
  10275. var agregator = new FulFillmentAgregator();
  10276. agregator.target = promises.length;
  10277. agregator.rootPromise = newPromise;
  10278. if (promises.length) {
  10279. for (var index = 0; index < promises.length; index++) {
  10280. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10281. }
  10282. }
  10283. else {
  10284. newPromise._resolve([]);
  10285. }
  10286. return newPromise;
  10287. };
  10288. InternalPromise.race = function (promises) {
  10289. var newPromise = new InternalPromise();
  10290. if (promises.length) {
  10291. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10292. var promise = promises_1[_i];
  10293. promise.then(function (value) {
  10294. if (newPromise) {
  10295. newPromise._resolve(value);
  10296. newPromise = null;
  10297. }
  10298. return null;
  10299. }, function (reason) {
  10300. if (newPromise) {
  10301. newPromise._reject(reason);
  10302. newPromise = null;
  10303. }
  10304. });
  10305. }
  10306. }
  10307. return newPromise;
  10308. };
  10309. return InternalPromise;
  10310. }());
  10311. /**
  10312. * Helper class that provides a small promise polyfill
  10313. */
  10314. var PromisePolyfill = /** @class */ (function () {
  10315. function PromisePolyfill() {
  10316. }
  10317. /**
  10318. * Static function used to check if the polyfill is required
  10319. * If this is the case then the function will inject the polyfill to window.Promise
  10320. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10321. */
  10322. PromisePolyfill.Apply = function (force) {
  10323. if (force === void 0) { force = false; }
  10324. if (force || typeof Promise === 'undefined') {
  10325. var root = window;
  10326. root.Promise = InternalPromise;
  10327. }
  10328. };
  10329. return PromisePolyfill;
  10330. }());
  10331. BABYLON.PromisePolyfill = PromisePolyfill;
  10332. })(BABYLON || (BABYLON = {}));
  10333. //# sourceMappingURL=babylon.promise.js.map
  10334. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10335. var BABYLON;
  10336. (function (BABYLON) {
  10337. /**
  10338. * Helper class to push actions to a pool of workers.
  10339. */
  10340. var WorkerPool = /** @class */ (function () {
  10341. /**
  10342. * Constructor
  10343. * @param workers Array of workers to use for actions
  10344. */
  10345. function WorkerPool(workers) {
  10346. this._pendingActions = new Array();
  10347. this._workerInfos = workers.map(function (worker) { return ({
  10348. worker: worker,
  10349. active: false
  10350. }); });
  10351. }
  10352. /**
  10353. * Terminates all workers and clears any pending actions.
  10354. */
  10355. WorkerPool.prototype.dispose = function () {
  10356. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10357. var workerInfo = _a[_i];
  10358. workerInfo.worker.terminate();
  10359. }
  10360. delete this._workerInfos;
  10361. delete this._pendingActions;
  10362. };
  10363. /**
  10364. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10365. * pended until a worker has completed its action.
  10366. * @param action The action to perform. Call onComplete when the action is complete.
  10367. */
  10368. WorkerPool.prototype.push = function (action) {
  10369. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10370. var workerInfo = _a[_i];
  10371. if (!workerInfo.active) {
  10372. this._execute(workerInfo, action);
  10373. return;
  10374. }
  10375. }
  10376. this._pendingActions.push(action);
  10377. };
  10378. WorkerPool.prototype._execute = function (workerInfo, action) {
  10379. var _this = this;
  10380. workerInfo.active = true;
  10381. action(workerInfo.worker, function () {
  10382. workerInfo.active = false;
  10383. var nextAction = _this._pendingActions.shift();
  10384. if (nextAction) {
  10385. _this._execute(workerInfo, nextAction);
  10386. }
  10387. });
  10388. };
  10389. return WorkerPool;
  10390. }());
  10391. BABYLON.WorkerPool = WorkerPool;
  10392. })(BABYLON || (BABYLON = {}));
  10393. //# sourceMappingURL=babylon.workerPool.js.map
  10394. var BABYLON;
  10395. (function (BABYLON) {
  10396. /**
  10397. * @hidden
  10398. **/
  10399. var _AlphaState = /** @class */ (function () {
  10400. /**
  10401. * Initializes the state.
  10402. */
  10403. function _AlphaState() {
  10404. this._isAlphaBlendDirty = false;
  10405. this._isBlendFunctionParametersDirty = false;
  10406. this._isBlendEquationParametersDirty = false;
  10407. this._isBlendConstantsDirty = false;
  10408. this._alphaBlend = false;
  10409. this._blendFunctionParameters = new Array(4);
  10410. this._blendEquationParameters = new Array(2);
  10411. this._blendConstants = new Array(4);
  10412. this.reset();
  10413. }
  10414. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10415. get: function () {
  10416. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10422. get: function () {
  10423. return this._alphaBlend;
  10424. },
  10425. set: function (value) {
  10426. if (this._alphaBlend === value) {
  10427. return;
  10428. }
  10429. this._alphaBlend = value;
  10430. this._isAlphaBlendDirty = true;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10436. if (this._blendConstants[0] === r &&
  10437. this._blendConstants[1] === g &&
  10438. this._blendConstants[2] === b &&
  10439. this._blendConstants[3] === a) {
  10440. return;
  10441. }
  10442. this._blendConstants[0] = r;
  10443. this._blendConstants[1] = g;
  10444. this._blendConstants[2] = b;
  10445. this._blendConstants[3] = a;
  10446. this._isBlendConstantsDirty = true;
  10447. };
  10448. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10449. if (this._blendFunctionParameters[0] === value0 &&
  10450. this._blendFunctionParameters[1] === value1 &&
  10451. this._blendFunctionParameters[2] === value2 &&
  10452. this._blendFunctionParameters[3] === value3) {
  10453. return;
  10454. }
  10455. this._blendFunctionParameters[0] = value0;
  10456. this._blendFunctionParameters[1] = value1;
  10457. this._blendFunctionParameters[2] = value2;
  10458. this._blendFunctionParameters[3] = value3;
  10459. this._isBlendFunctionParametersDirty = true;
  10460. };
  10461. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10462. if (this._blendEquationParameters[0] === rgb &&
  10463. this._blendEquationParameters[1] === alpha) {
  10464. return;
  10465. }
  10466. this._blendEquationParameters[0] = rgb;
  10467. this._blendEquationParameters[1] = alpha;
  10468. this._isBlendEquationParametersDirty = true;
  10469. };
  10470. _AlphaState.prototype.reset = function () {
  10471. this._alphaBlend = false;
  10472. this._blendFunctionParameters[0] = null;
  10473. this._blendFunctionParameters[1] = null;
  10474. this._blendFunctionParameters[2] = null;
  10475. this._blendFunctionParameters[3] = null;
  10476. this._blendEquationParameters[0] = null;
  10477. this._blendEquationParameters[1] = null;
  10478. this._blendConstants[0] = null;
  10479. this._blendConstants[1] = null;
  10480. this._blendConstants[2] = null;
  10481. this._blendConstants[3] = null;
  10482. this._isAlphaBlendDirty = true;
  10483. this._isBlendFunctionParametersDirty = false;
  10484. this._isBlendEquationParametersDirty = false;
  10485. this._isBlendConstantsDirty = false;
  10486. };
  10487. _AlphaState.prototype.apply = function (gl) {
  10488. if (!this.isDirty) {
  10489. return;
  10490. }
  10491. // Alpha blend
  10492. if (this._isAlphaBlendDirty) {
  10493. if (this._alphaBlend) {
  10494. gl.enable(gl.BLEND);
  10495. }
  10496. else {
  10497. gl.disable(gl.BLEND);
  10498. }
  10499. this._isAlphaBlendDirty = false;
  10500. }
  10501. // Alpha function
  10502. if (this._isBlendFunctionParametersDirty) {
  10503. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10504. this._isBlendFunctionParametersDirty = false;
  10505. }
  10506. // Alpha equation
  10507. if (this._isBlendEquationParametersDirty) {
  10508. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10509. this._isBlendEquationParametersDirty = false;
  10510. }
  10511. // Constants
  10512. if (this._isBlendConstantsDirty) {
  10513. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10514. this._isBlendConstantsDirty = false;
  10515. }
  10516. };
  10517. return _AlphaState;
  10518. }());
  10519. BABYLON._AlphaState = _AlphaState;
  10520. })(BABYLON || (BABYLON = {}));
  10521. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10522. var BABYLON;
  10523. (function (BABYLON) {
  10524. /**
  10525. * @hidden
  10526. **/
  10527. var _DepthCullingState = /** @class */ (function () {
  10528. /**
  10529. * Initializes the state.
  10530. */
  10531. function _DepthCullingState() {
  10532. this._isDepthTestDirty = false;
  10533. this._isDepthMaskDirty = false;
  10534. this._isDepthFuncDirty = false;
  10535. this._isCullFaceDirty = false;
  10536. this._isCullDirty = false;
  10537. this._isZOffsetDirty = false;
  10538. this._isFrontFaceDirty = false;
  10539. this.reset();
  10540. }
  10541. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10542. get: function () {
  10543. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10544. },
  10545. enumerable: true,
  10546. configurable: true
  10547. });
  10548. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10549. get: function () {
  10550. return this._zOffset;
  10551. },
  10552. set: function (value) {
  10553. if (this._zOffset === value) {
  10554. return;
  10555. }
  10556. this._zOffset = value;
  10557. this._isZOffsetDirty = true;
  10558. },
  10559. enumerable: true,
  10560. configurable: true
  10561. });
  10562. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10563. get: function () {
  10564. return this._cullFace;
  10565. },
  10566. set: function (value) {
  10567. if (this._cullFace === value) {
  10568. return;
  10569. }
  10570. this._cullFace = value;
  10571. this._isCullFaceDirty = true;
  10572. },
  10573. enumerable: true,
  10574. configurable: true
  10575. });
  10576. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10577. get: function () {
  10578. return this._cull;
  10579. },
  10580. set: function (value) {
  10581. if (this._cull === value) {
  10582. return;
  10583. }
  10584. this._cull = value;
  10585. this._isCullDirty = true;
  10586. },
  10587. enumerable: true,
  10588. configurable: true
  10589. });
  10590. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10591. get: function () {
  10592. return this._depthFunc;
  10593. },
  10594. set: function (value) {
  10595. if (this._depthFunc === value) {
  10596. return;
  10597. }
  10598. this._depthFunc = value;
  10599. this._isDepthFuncDirty = true;
  10600. },
  10601. enumerable: true,
  10602. configurable: true
  10603. });
  10604. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10605. get: function () {
  10606. return this._depthMask;
  10607. },
  10608. set: function (value) {
  10609. if (this._depthMask === value) {
  10610. return;
  10611. }
  10612. this._depthMask = value;
  10613. this._isDepthMaskDirty = true;
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10619. get: function () {
  10620. return this._depthTest;
  10621. },
  10622. set: function (value) {
  10623. if (this._depthTest === value) {
  10624. return;
  10625. }
  10626. this._depthTest = value;
  10627. this._isDepthTestDirty = true;
  10628. },
  10629. enumerable: true,
  10630. configurable: true
  10631. });
  10632. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10633. get: function () {
  10634. return this._frontFace;
  10635. },
  10636. set: function (value) {
  10637. if (this._frontFace === value) {
  10638. return;
  10639. }
  10640. this._frontFace = value;
  10641. this._isFrontFaceDirty = true;
  10642. },
  10643. enumerable: true,
  10644. configurable: true
  10645. });
  10646. _DepthCullingState.prototype.reset = function () {
  10647. this._depthMask = true;
  10648. this._depthTest = true;
  10649. this._depthFunc = null;
  10650. this._cullFace = null;
  10651. this._cull = null;
  10652. this._zOffset = 0;
  10653. this._frontFace = null;
  10654. this._isDepthTestDirty = true;
  10655. this._isDepthMaskDirty = true;
  10656. this._isDepthFuncDirty = false;
  10657. this._isCullFaceDirty = false;
  10658. this._isCullDirty = false;
  10659. this._isZOffsetDirty = false;
  10660. this._isFrontFaceDirty = false;
  10661. };
  10662. _DepthCullingState.prototype.apply = function (gl) {
  10663. if (!this.isDirty) {
  10664. return;
  10665. }
  10666. // Cull
  10667. if (this._isCullDirty) {
  10668. if (this.cull) {
  10669. gl.enable(gl.CULL_FACE);
  10670. }
  10671. else {
  10672. gl.disable(gl.CULL_FACE);
  10673. }
  10674. this._isCullDirty = false;
  10675. }
  10676. // Cull face
  10677. if (this._isCullFaceDirty) {
  10678. gl.cullFace(this.cullFace);
  10679. this._isCullFaceDirty = false;
  10680. }
  10681. // Depth mask
  10682. if (this._isDepthMaskDirty) {
  10683. gl.depthMask(this.depthMask);
  10684. this._isDepthMaskDirty = false;
  10685. }
  10686. // Depth test
  10687. if (this._isDepthTestDirty) {
  10688. if (this.depthTest) {
  10689. gl.enable(gl.DEPTH_TEST);
  10690. }
  10691. else {
  10692. gl.disable(gl.DEPTH_TEST);
  10693. }
  10694. this._isDepthTestDirty = false;
  10695. }
  10696. // Depth func
  10697. if (this._isDepthFuncDirty) {
  10698. gl.depthFunc(this.depthFunc);
  10699. this._isDepthFuncDirty = false;
  10700. }
  10701. // zOffset
  10702. if (this._isZOffsetDirty) {
  10703. if (this.zOffset) {
  10704. gl.enable(gl.POLYGON_OFFSET_FILL);
  10705. gl.polygonOffset(this.zOffset, 0);
  10706. }
  10707. else {
  10708. gl.disable(gl.POLYGON_OFFSET_FILL);
  10709. }
  10710. this._isZOffsetDirty = false;
  10711. }
  10712. // Front face
  10713. if (this._isFrontFaceDirty) {
  10714. gl.frontFace(this.frontFace);
  10715. this._isFrontFaceDirty = false;
  10716. }
  10717. };
  10718. return _DepthCullingState;
  10719. }());
  10720. BABYLON._DepthCullingState = _DepthCullingState;
  10721. })(BABYLON || (BABYLON = {}));
  10722. //# sourceMappingURL=babylon.depthCullingState.js.map
  10723. var BABYLON;
  10724. (function (BABYLON) {
  10725. /**
  10726. * @hidden
  10727. **/
  10728. var _StencilState = /** @class */ (function () {
  10729. function _StencilState() {
  10730. this._isStencilTestDirty = false;
  10731. this._isStencilMaskDirty = false;
  10732. this._isStencilFuncDirty = false;
  10733. this._isStencilOpDirty = false;
  10734. this.reset();
  10735. }
  10736. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10737. get: function () {
  10738. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10744. get: function () {
  10745. return this._stencilFunc;
  10746. },
  10747. set: function (value) {
  10748. if (this._stencilFunc === value) {
  10749. return;
  10750. }
  10751. this._stencilFunc = value;
  10752. this._isStencilFuncDirty = true;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10758. get: function () {
  10759. return this._stencilFuncRef;
  10760. },
  10761. set: function (value) {
  10762. if (this._stencilFuncRef === value) {
  10763. return;
  10764. }
  10765. this._stencilFuncRef = value;
  10766. this._isStencilFuncDirty = true;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10772. get: function () {
  10773. return this._stencilFuncMask;
  10774. },
  10775. set: function (value) {
  10776. if (this._stencilFuncMask === value) {
  10777. return;
  10778. }
  10779. this._stencilFuncMask = value;
  10780. this._isStencilFuncDirty = true;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10786. get: function () {
  10787. return this._stencilOpStencilFail;
  10788. },
  10789. set: function (value) {
  10790. if (this._stencilOpStencilFail === value) {
  10791. return;
  10792. }
  10793. this._stencilOpStencilFail = value;
  10794. this._isStencilOpDirty = true;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10800. get: function () {
  10801. return this._stencilOpDepthFail;
  10802. },
  10803. set: function (value) {
  10804. if (this._stencilOpDepthFail === value) {
  10805. return;
  10806. }
  10807. this._stencilOpDepthFail = value;
  10808. this._isStencilOpDirty = true;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10814. get: function () {
  10815. return this._stencilOpStencilDepthPass;
  10816. },
  10817. set: function (value) {
  10818. if (this._stencilOpStencilDepthPass === value) {
  10819. return;
  10820. }
  10821. this._stencilOpStencilDepthPass = value;
  10822. this._isStencilOpDirty = true;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10828. get: function () {
  10829. return this._stencilMask;
  10830. },
  10831. set: function (value) {
  10832. if (this._stencilMask === value) {
  10833. return;
  10834. }
  10835. this._stencilMask = value;
  10836. this._isStencilMaskDirty = true;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10842. get: function () {
  10843. return this._stencilTest;
  10844. },
  10845. set: function (value) {
  10846. if (this._stencilTest === value) {
  10847. return;
  10848. }
  10849. this._stencilTest = value;
  10850. this._isStencilTestDirty = true;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. _StencilState.prototype.reset = function () {
  10856. this._stencilTest = false;
  10857. this._stencilMask = 0xFF;
  10858. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10859. this._stencilFuncRef = 1;
  10860. this._stencilFuncMask = 0xFF;
  10861. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10862. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10863. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10864. this._isStencilTestDirty = true;
  10865. this._isStencilMaskDirty = true;
  10866. this._isStencilFuncDirty = true;
  10867. this._isStencilOpDirty = true;
  10868. };
  10869. _StencilState.prototype.apply = function (gl) {
  10870. if (!this.isDirty) {
  10871. return;
  10872. }
  10873. // Stencil test
  10874. if (this._isStencilTestDirty) {
  10875. if (this.stencilTest) {
  10876. gl.enable(gl.STENCIL_TEST);
  10877. }
  10878. else {
  10879. gl.disable(gl.STENCIL_TEST);
  10880. }
  10881. this._isStencilTestDirty = false;
  10882. }
  10883. // Stencil mask
  10884. if (this._isStencilMaskDirty) {
  10885. gl.stencilMask(this.stencilMask);
  10886. this._isStencilMaskDirty = false;
  10887. }
  10888. // Stencil func
  10889. if (this._isStencilFuncDirty) {
  10890. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10891. this._isStencilFuncDirty = false;
  10892. }
  10893. // Stencil op
  10894. if (this._isStencilOpDirty) {
  10895. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10896. this._isStencilOpDirty = false;
  10897. }
  10898. };
  10899. return _StencilState;
  10900. }());
  10901. BABYLON._StencilState = _StencilState;
  10902. })(BABYLON || (BABYLON = {}));
  10903. //# sourceMappingURL=babylon.stencilState.js.map
  10904. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10905. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10906. s = arguments[i];
  10907. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10908. t[p] = s[p];
  10909. }
  10910. return t;
  10911. };
  10912. var BABYLON;
  10913. (function (BABYLON) {
  10914. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10915. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10916. };
  10917. var compileRawShader = function (gl, source, type) {
  10918. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10919. gl.shaderSource(shader, source);
  10920. gl.compileShader(shader);
  10921. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10922. var log = gl.getShaderInfoLog(shader);
  10923. if (log) {
  10924. throw new Error(log);
  10925. }
  10926. }
  10927. if (!shader) {
  10928. throw new Error("Something went wrong while compile the shader.");
  10929. }
  10930. return shader;
  10931. };
  10932. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10933. var magFilter = gl.NEAREST;
  10934. var minFilter = gl.NEAREST;
  10935. switch (samplingMode) {
  10936. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10937. magFilter = gl.LINEAR;
  10938. if (generateMipMaps) {
  10939. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10940. }
  10941. else {
  10942. minFilter = gl.LINEAR;
  10943. }
  10944. break;
  10945. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10946. magFilter = gl.LINEAR;
  10947. if (generateMipMaps) {
  10948. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10949. }
  10950. else {
  10951. minFilter = gl.LINEAR;
  10952. }
  10953. break;
  10954. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10955. magFilter = gl.NEAREST;
  10956. if (generateMipMaps) {
  10957. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10958. }
  10959. else {
  10960. minFilter = gl.NEAREST;
  10961. }
  10962. break;
  10963. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10964. magFilter = gl.NEAREST;
  10965. if (generateMipMaps) {
  10966. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10967. }
  10968. else {
  10969. minFilter = gl.NEAREST;
  10970. }
  10971. break;
  10972. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10973. magFilter = gl.NEAREST;
  10974. if (generateMipMaps) {
  10975. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10976. }
  10977. else {
  10978. minFilter = gl.LINEAR;
  10979. }
  10980. break;
  10981. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10982. magFilter = gl.NEAREST;
  10983. if (generateMipMaps) {
  10984. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10985. }
  10986. else {
  10987. minFilter = gl.LINEAR;
  10988. }
  10989. break;
  10990. case BABYLON.Texture.NEAREST_LINEAR:
  10991. magFilter = gl.NEAREST;
  10992. minFilter = gl.LINEAR;
  10993. break;
  10994. case BABYLON.Texture.NEAREST_NEAREST:
  10995. magFilter = gl.NEAREST;
  10996. minFilter = gl.NEAREST;
  10997. break;
  10998. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10999. magFilter = gl.LINEAR;
  11000. if (generateMipMaps) {
  11001. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11002. }
  11003. else {
  11004. minFilter = gl.NEAREST;
  11005. }
  11006. break;
  11007. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11008. magFilter = gl.LINEAR;
  11009. if (generateMipMaps) {
  11010. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11011. }
  11012. else {
  11013. minFilter = gl.NEAREST;
  11014. }
  11015. break;
  11016. case BABYLON.Texture.LINEAR_LINEAR:
  11017. magFilter = gl.LINEAR;
  11018. minFilter = gl.LINEAR;
  11019. break;
  11020. case BABYLON.Texture.LINEAR_NEAREST:
  11021. magFilter = gl.LINEAR;
  11022. minFilter = gl.NEAREST;
  11023. break;
  11024. }
  11025. return {
  11026. min: minFilter,
  11027. mag: magFilter
  11028. };
  11029. };
  11030. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11031. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11032. var img;
  11033. var onload = function () {
  11034. loadedImages[index] = img;
  11035. loadedImages._internalCount++;
  11036. if (scene) {
  11037. scene._removePendingData(img);
  11038. }
  11039. if (loadedImages._internalCount === 6) {
  11040. onfinish(loadedImages);
  11041. }
  11042. };
  11043. var onerror = function (message, exception) {
  11044. if (scene) {
  11045. scene._removePendingData(img);
  11046. }
  11047. if (onErrorCallBack) {
  11048. onErrorCallBack(message, exception);
  11049. }
  11050. };
  11051. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11052. if (scene) {
  11053. scene._addPendingData(img);
  11054. }
  11055. };
  11056. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11057. if (onError === void 0) { onError = null; }
  11058. var loadedImages = [];
  11059. loadedImages._internalCount = 0;
  11060. for (var index = 0; index < 6; index++) {
  11061. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11062. }
  11063. };
  11064. var BufferPointer = /** @class */ (function () {
  11065. function BufferPointer() {
  11066. }
  11067. return BufferPointer;
  11068. }());
  11069. /**
  11070. * Interface for attribute information associated with buffer instanciation
  11071. */
  11072. var InstancingAttributeInfo = /** @class */ (function () {
  11073. function InstancingAttributeInfo() {
  11074. }
  11075. return InstancingAttributeInfo;
  11076. }());
  11077. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11078. /**
  11079. * Define options used to create a render target texture
  11080. */
  11081. var RenderTargetCreationOptions = /** @class */ (function () {
  11082. function RenderTargetCreationOptions() {
  11083. }
  11084. return RenderTargetCreationOptions;
  11085. }());
  11086. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11087. /**
  11088. * Define options used to create a depth texture
  11089. */
  11090. var DepthTextureCreationOptions = /** @class */ (function () {
  11091. function DepthTextureCreationOptions() {
  11092. }
  11093. return DepthTextureCreationOptions;
  11094. }());
  11095. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11096. /**
  11097. * Class used to describe the capabilities of the engine relatively to the current browser
  11098. */
  11099. var EngineCapabilities = /** @class */ (function () {
  11100. function EngineCapabilities() {
  11101. }
  11102. return EngineCapabilities;
  11103. }());
  11104. BABYLON.EngineCapabilities = EngineCapabilities;
  11105. /**
  11106. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11107. */
  11108. var Engine = /** @class */ (function () {
  11109. /**
  11110. * Creates a new engine
  11111. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11112. * @param antialias defines enable antialiasing (default: false)
  11113. * @param options defines further options to be sent to the getContext() function
  11114. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11115. */
  11116. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11117. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11118. var _this = this;
  11119. // Public members
  11120. /**
  11121. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11122. */
  11123. this.forcePOTTextures = false;
  11124. /**
  11125. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11126. */
  11127. this.isFullscreen = false;
  11128. /**
  11129. * Gets a boolean indicating if the pointer is currently locked
  11130. */
  11131. this.isPointerLock = false;
  11132. /**
  11133. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11134. */
  11135. this.cullBackFaces = true;
  11136. /**
  11137. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11138. */
  11139. this.renderEvenInBackground = true;
  11140. /**
  11141. * Gets or sets a boolean indicating that cache can be kept between frames
  11142. */
  11143. this.preventCacheWipeBetweenFrames = false;
  11144. /**
  11145. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11146. **/
  11147. this.enableOfflineSupport = false;
  11148. /**
  11149. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11150. **/
  11151. this.disableManifestCheck = false;
  11152. /**
  11153. * Gets the list of created scenes
  11154. */
  11155. this.scenes = new Array();
  11156. /**
  11157. * Gets the list of created postprocesses
  11158. */
  11159. this.postProcesses = new Array();
  11160. // Observables
  11161. /**
  11162. * Observable event triggered each time the rendering canvas is resized
  11163. */
  11164. this.onResizeObservable = new BABYLON.Observable();
  11165. /**
  11166. * Observable event triggered each time the canvas loses focus
  11167. */
  11168. this.onCanvasBlurObservable = new BABYLON.Observable();
  11169. /**
  11170. * Observable event triggered each time the canvas gains focus
  11171. */
  11172. this.onCanvasFocusObservable = new BABYLON.Observable();
  11173. /**
  11174. * Observable event triggered each time the canvas receives pointerout event
  11175. */
  11176. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11177. /**
  11178. * Observable event triggered before each texture is initialized
  11179. */
  11180. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11181. //WebVR
  11182. this._vrDisplay = undefined;
  11183. this._vrSupported = false;
  11184. this._vrExclusivePointerMode = false;
  11185. // Uniform buffers list
  11186. /**
  11187. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11188. */
  11189. this.disableUniformBuffers = false;
  11190. /** @hidden */
  11191. this._uniformBuffers = new Array();
  11192. // Observables
  11193. /**
  11194. * Observable raised when the engine begins a new frame
  11195. */
  11196. this.onBeginFrameObservable = new BABYLON.Observable();
  11197. /**
  11198. * Observable raised when the engine ends the current frame
  11199. */
  11200. this.onEndFrameObservable = new BABYLON.Observable();
  11201. /**
  11202. * Observable raised when the engine is about to compile a shader
  11203. */
  11204. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11205. /**
  11206. * Observable raised when the engine has jsut compiled a shader
  11207. */
  11208. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11209. this._windowIsBackground = false;
  11210. this._webGLVersion = 1.0;
  11211. /** @hidden */
  11212. this._badOS = false;
  11213. /** @hidden */
  11214. this._badDesktopOS = false;
  11215. /**
  11216. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11217. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11218. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11219. */
  11220. this.disableTextureBindingOptimization = false;
  11221. /**
  11222. * Observable signaled when VR display mode changes
  11223. */
  11224. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11225. /**
  11226. * Observable signaled when VR request present is complete
  11227. */
  11228. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11229. /**
  11230. * Observable signaled when VR request present starts
  11231. */
  11232. this.onVRRequestPresentStart = new BABYLON.Observable();
  11233. this._colorWrite = true;
  11234. /** @hidden */
  11235. this._drawCalls = new BABYLON.PerfCounter();
  11236. /** @hidden */
  11237. this._textureCollisions = new BABYLON.PerfCounter();
  11238. this._renderingQueueLaunched = false;
  11239. this._activeRenderLoops = new Array();
  11240. // Deterministic lockstepMaxSteps
  11241. this._deterministicLockstep = false;
  11242. this._lockstepMaxSteps = 4;
  11243. // Lost context
  11244. /**
  11245. * Observable signaled when a context lost event is raised
  11246. */
  11247. this.onContextLostObservable = new BABYLON.Observable();
  11248. /**
  11249. * Observable signaled when a context restored event is raised
  11250. */
  11251. this.onContextRestoredObservable = new BABYLON.Observable();
  11252. this._contextWasLost = false;
  11253. this._doNotHandleContextLost = false;
  11254. // FPS
  11255. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11256. this._fps = 60;
  11257. this._deltaTime = 0;
  11258. /**
  11259. * Turn this value on if you want to pause FPS computation when in background
  11260. */
  11261. this.disablePerformanceMonitorInBackground = false;
  11262. // States
  11263. /** @hidden */
  11264. this._depthCullingState = new BABYLON._DepthCullingState();
  11265. /** @hidden */
  11266. this._stencilState = new BABYLON._StencilState();
  11267. /** @hidden */
  11268. this._alphaState = new BABYLON._AlphaState();
  11269. /** @hidden */
  11270. this._alphaMode = Engine.ALPHA_DISABLE;
  11271. // Cache
  11272. this._internalTexturesCache = new Array();
  11273. /** @hidden */
  11274. this._activeChannel = 0;
  11275. this._currentTextureChannel = -1;
  11276. /** @hidden */
  11277. this._boundTexturesCache = {};
  11278. this._compiledEffects = {};
  11279. this._vertexAttribArraysEnabled = [];
  11280. this._uintIndicesCurrentlySet = false;
  11281. this._currentBoundBuffer = new Array();
  11282. this._currentBufferPointers = new Array();
  11283. this._currentInstanceLocations = new Array();
  11284. this._currentInstanceBuffers = new Array();
  11285. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11286. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11287. this._vaoRecordInProgress = false;
  11288. this._mustWipeVertexAttributes = false;
  11289. this._nextFreeTextureSlots = new Array();
  11290. this._maxSimultaneousTextures = 0;
  11291. this._activeRequests = new Array();
  11292. // Hardware supported Compressed Textures
  11293. this._texturesSupported = new Array();
  11294. this._onVRFullScreenTriggered = function () {
  11295. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11296. //get the old size before we change
  11297. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11298. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11299. //get the width and height, change the render size
  11300. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11301. _this.setHardwareScalingLevel(1);
  11302. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11303. }
  11304. else {
  11305. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11306. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11307. }
  11308. };
  11309. this._boundUniforms = {};
  11310. // Register promises
  11311. BABYLON.PromisePolyfill.Apply();
  11312. var canvas = null;
  11313. Engine.Instances.push(this);
  11314. if (!canvasOrContext) {
  11315. return;
  11316. }
  11317. options = options || {};
  11318. if (canvasOrContext.getContext) {
  11319. canvas = canvasOrContext;
  11320. this._renderingCanvas = canvas;
  11321. if (antialias != null) {
  11322. options.antialias = antialias;
  11323. }
  11324. if (options.deterministicLockstep === undefined) {
  11325. options.deterministicLockstep = false;
  11326. }
  11327. if (options.lockstepMaxSteps === undefined) {
  11328. options.lockstepMaxSteps = 4;
  11329. }
  11330. if (options.preserveDrawingBuffer === undefined) {
  11331. options.preserveDrawingBuffer = false;
  11332. }
  11333. if (options.audioEngine === undefined) {
  11334. options.audioEngine = true;
  11335. }
  11336. if (options.stencil === undefined) {
  11337. options.stencil = true;
  11338. }
  11339. this._deterministicLockstep = options.deterministicLockstep;
  11340. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11341. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11342. // Exceptions
  11343. if (navigator && navigator.userAgent) {
  11344. var ua = navigator.userAgent;
  11345. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11346. var exception = _a[_i];
  11347. var key = exception.key;
  11348. var targets = exception.targets;
  11349. if (ua.indexOf(key) > -1) {
  11350. if (exception.capture && exception.captureConstraint) {
  11351. var capture = exception.capture;
  11352. var constraint = exception.captureConstraint;
  11353. var regex = new RegExp(capture);
  11354. var matches = regex.exec(ua);
  11355. if (matches && matches.length > 0) {
  11356. var capturedValue = parseInt(matches[matches.length - 1]);
  11357. if (capturedValue >= constraint) {
  11358. continue;
  11359. }
  11360. }
  11361. }
  11362. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11363. var target = targets_1[_b];
  11364. switch (target) {
  11365. case "uniformBuffer":
  11366. this.disableUniformBuffers = true;
  11367. break;
  11368. case "textureBindingOptimization":
  11369. this.disableTextureBindingOptimization = true;
  11370. break;
  11371. }
  11372. }
  11373. }
  11374. }
  11375. }
  11376. // GL
  11377. if (!options.disableWebGL2Support) {
  11378. try {
  11379. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11380. if (this._gl) {
  11381. this._webGLVersion = 2.0;
  11382. }
  11383. }
  11384. catch (e) {
  11385. // Do nothing
  11386. }
  11387. }
  11388. if (!this._gl) {
  11389. if (!canvas) {
  11390. throw new Error("The provided canvas is null or undefined.");
  11391. }
  11392. try {
  11393. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11394. }
  11395. catch (e) {
  11396. throw new Error("WebGL not supported");
  11397. }
  11398. }
  11399. if (!this._gl) {
  11400. throw new Error("WebGL not supported");
  11401. }
  11402. this._onCanvasFocus = function () {
  11403. _this.onCanvasFocusObservable.notifyObservers(_this);
  11404. };
  11405. this._onCanvasBlur = function () {
  11406. _this.onCanvasBlurObservable.notifyObservers(_this);
  11407. };
  11408. canvas.addEventListener("focus", this._onCanvasFocus);
  11409. canvas.addEventListener("blur", this._onCanvasBlur);
  11410. this._onBlur = function () {
  11411. if (_this.disablePerformanceMonitorInBackground) {
  11412. _this._performanceMonitor.disable();
  11413. }
  11414. _this._windowIsBackground = true;
  11415. };
  11416. this._onFocus = function () {
  11417. if (_this.disablePerformanceMonitorInBackground) {
  11418. _this._performanceMonitor.enable();
  11419. }
  11420. _this._windowIsBackground = false;
  11421. };
  11422. this._onCanvasPointerOut = function (ev) {
  11423. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11424. };
  11425. window.addEventListener("blur", this._onBlur);
  11426. window.addEventListener("focus", this._onFocus);
  11427. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11428. // Context lost
  11429. if (!this._doNotHandleContextLost) {
  11430. this._onContextLost = function (evt) {
  11431. evt.preventDefault();
  11432. _this._contextWasLost = true;
  11433. BABYLON.Tools.Warn("WebGL context lost.");
  11434. _this.onContextLostObservable.notifyObservers(_this);
  11435. };
  11436. this._onContextRestored = function (evt) {
  11437. // Adding a timeout to avoid race condition at browser level
  11438. setTimeout(function () {
  11439. // Rebuild gl context
  11440. _this._initGLContext();
  11441. // Rebuild effects
  11442. _this._rebuildEffects();
  11443. // Rebuild textures
  11444. _this._rebuildInternalTextures();
  11445. // Rebuild buffers
  11446. _this._rebuildBuffers();
  11447. // Cache
  11448. _this.wipeCaches(true);
  11449. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11450. _this.onContextRestoredObservable.notifyObservers(_this);
  11451. _this._contextWasLost = false;
  11452. }, 0);
  11453. };
  11454. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11455. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11456. }
  11457. }
  11458. else {
  11459. this._gl = canvasOrContext;
  11460. this._renderingCanvas = this._gl.canvas;
  11461. if (this._gl.renderbufferStorageMultisample) {
  11462. this._webGLVersion = 2.0;
  11463. }
  11464. options.stencil = this._gl.getContextAttributes().stencil;
  11465. }
  11466. // Viewport
  11467. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11468. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11469. this.resize();
  11470. this._isStencilEnable = options.stencil ? true : false;
  11471. this._initGLContext();
  11472. if (canvas) {
  11473. // Fullscreen
  11474. this._onFullscreenChange = function () {
  11475. if (document.fullscreen !== undefined) {
  11476. _this.isFullscreen = document.fullscreen;
  11477. }
  11478. else if (document.mozFullScreen !== undefined) {
  11479. _this.isFullscreen = document.mozFullScreen;
  11480. }
  11481. else if (document.webkitIsFullScreen !== undefined) {
  11482. _this.isFullscreen = document.webkitIsFullScreen;
  11483. }
  11484. else if (document.msIsFullScreen !== undefined) {
  11485. _this.isFullscreen = document.msIsFullScreen;
  11486. }
  11487. // Pointer lock
  11488. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11489. canvas.requestPointerLock = canvas.requestPointerLock ||
  11490. canvas.msRequestPointerLock ||
  11491. canvas.mozRequestPointerLock ||
  11492. canvas.webkitRequestPointerLock;
  11493. if (canvas.requestPointerLock) {
  11494. canvas.requestPointerLock();
  11495. }
  11496. }
  11497. };
  11498. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11499. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11500. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11501. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11502. // Pointer lock
  11503. this._onPointerLockChange = function () {
  11504. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11505. document.webkitPointerLockElement === canvas ||
  11506. document.msPointerLockElement === canvas ||
  11507. document.pointerLockElement === canvas);
  11508. };
  11509. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11510. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11511. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11512. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11513. this._onVRDisplayPointerRestricted = function () {
  11514. if (canvas) {
  11515. canvas.requestPointerLock();
  11516. }
  11517. };
  11518. this._onVRDisplayPointerUnrestricted = function () {
  11519. document.exitPointerLock();
  11520. };
  11521. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11522. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11523. }
  11524. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11525. Engine.audioEngine = new BABYLON.AudioEngine();
  11526. }
  11527. // Prepare buffer pointers
  11528. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11529. this._currentBufferPointers[i] = new BufferPointer();
  11530. }
  11531. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11532. // Load WebVR Devices
  11533. if (options.autoEnableWebVR) {
  11534. this.initWebVR();
  11535. }
  11536. // Detect if we are running on a faulty buggy OS.
  11537. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11538. // Detect if we are running on a faulty buggy desktop OS.
  11539. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11540. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11541. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11542. }
  11543. Object.defineProperty(Engine, "LastCreatedEngine", {
  11544. /**
  11545. * Gets the latest created engine
  11546. */
  11547. get: function () {
  11548. if (Engine.Instances.length === 0) {
  11549. return null;
  11550. }
  11551. return Engine.Instances[Engine.Instances.length - 1];
  11552. },
  11553. enumerable: true,
  11554. configurable: true
  11555. });
  11556. Object.defineProperty(Engine, "LastCreatedScene", {
  11557. /**
  11558. * Gets the latest created scene
  11559. */
  11560. get: function () {
  11561. var lastCreatedEngine = Engine.LastCreatedEngine;
  11562. if (!lastCreatedEngine) {
  11563. return null;
  11564. }
  11565. if (lastCreatedEngine.scenes.length === 0) {
  11566. return null;
  11567. }
  11568. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11569. },
  11570. enumerable: true,
  11571. configurable: true
  11572. });
  11573. /**
  11574. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11575. * @param flag defines which part of the materials must be marked as dirty
  11576. * @param predicate defines a predicate used to filter which materials should be affected
  11577. */
  11578. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11579. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11580. var engine = Engine.Instances[engineIndex];
  11581. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11582. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11583. }
  11584. }
  11585. };
  11586. Object.defineProperty(Engine, "NEVER", {
  11587. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11588. get: function () {
  11589. return Engine._NEVER;
  11590. },
  11591. enumerable: true,
  11592. configurable: true
  11593. });
  11594. Object.defineProperty(Engine, "ALWAYS", {
  11595. /** 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 */
  11596. get: function () {
  11597. return Engine._ALWAYS;
  11598. },
  11599. enumerable: true,
  11600. configurable: true
  11601. });
  11602. Object.defineProperty(Engine, "LESS", {
  11603. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11604. get: function () {
  11605. return Engine._LESS;
  11606. },
  11607. enumerable: true,
  11608. configurable: true
  11609. });
  11610. Object.defineProperty(Engine, "EQUAL", {
  11611. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11612. get: function () {
  11613. return Engine._EQUAL;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(Engine, "LEQUAL", {
  11619. /** 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 */
  11620. get: function () {
  11621. return Engine._LEQUAL;
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine, "GREATER", {
  11627. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11628. get: function () {
  11629. return Engine._GREATER;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "GEQUAL", {
  11635. /** 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 */
  11636. get: function () {
  11637. return Engine._GEQUAL;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "NOTEQUAL", {
  11643. /** 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 */
  11644. get: function () {
  11645. return Engine._NOTEQUAL;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "KEEP", {
  11651. /** Passed to stencilOperation to specify that stencil value must be kept */
  11652. get: function () {
  11653. return Engine._KEEP;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "REPLACE", {
  11659. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11660. get: function () {
  11661. return Engine._REPLACE;
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Engine, "INCR", {
  11667. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11668. get: function () {
  11669. return Engine._INCR;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Engine, "DECR", {
  11675. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11676. get: function () {
  11677. return Engine._DECR;
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(Engine, "INVERT", {
  11683. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11684. get: function () {
  11685. return Engine._INVERT;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine, "INCR_WRAP", {
  11691. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11692. get: function () {
  11693. return Engine._INCR_WRAP;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "DECR_WRAP", {
  11699. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11700. get: function () {
  11701. return Engine._DECR_WRAP;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11707. // Alpha
  11708. /** Defines that alpha blending is disabled */
  11709. get: function () {
  11710. return Engine._ALPHA_DISABLE;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11716. /** Defines that alpha blending to SRC + DEST */
  11717. get: function () {
  11718. return Engine._ALPHA_ONEONE;
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. Object.defineProperty(Engine, "ALPHA_ADD", {
  11724. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11725. get: function () {
  11726. return Engine._ALPHA_ADD;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11732. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11733. get: function () {
  11734. return Engine._ALPHA_COMBINE;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11740. /** Defines that alpha blending to DEST - SRC * DEST */
  11741. get: function () {
  11742. return Engine._ALPHA_SUBTRACT;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11748. /** Defines that alpha blending to SRC * DEST */
  11749. get: function () {
  11750. return Engine._ALPHA_MULTIPLY;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11756. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11757. get: function () {
  11758. return Engine._ALPHA_MAXIMIZED;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11764. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11765. get: function () {
  11766. return Engine._ALPHA_PREMULTIPLIED;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11772. /**
  11773. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11774. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11775. */
  11776. get: function () {
  11777. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11783. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11784. get: function () {
  11785. return Engine._ALPHA_INTERPOLATE;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11791. /**
  11792. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11793. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11794. */
  11795. get: function () {
  11796. return Engine._ALPHA_SCREENMODE;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11802. // Delays
  11803. /** Defines that the ressource is not delayed*/
  11804. get: function () {
  11805. return Engine._DELAYLOADSTATE_NONE;
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11811. /** Defines that the ressource was successfully delay loaded */
  11812. get: function () {
  11813. return Engine._DELAYLOADSTATE_LOADED;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11819. /** Defines that the ressource is currently delay loading */
  11820. get: function () {
  11821. return Engine._DELAYLOADSTATE_LOADING;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11827. /** Defines that the ressource is delayed and has not started loading */
  11828. get: function () {
  11829. return Engine._DELAYLOADSTATE_NOTLOADED;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11835. /** ALPHA */
  11836. get: function () {
  11837. return Engine._TEXTUREFORMAT_ALPHA;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11843. /** LUMINANCE */
  11844. get: function () {
  11845. return Engine._TEXTUREFORMAT_LUMINANCE;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11851. /**
  11852. * R32F
  11853. */
  11854. get: function () {
  11855. return Engine._TEXTUREFORMAT_R32F;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11861. /**
  11862. * RG32F
  11863. */
  11864. get: function () {
  11865. return Engine._TEXTUREFORMAT_RG32F;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11871. /**
  11872. * RGB32F
  11873. */
  11874. get: function () {
  11875. return Engine._TEXTUREFORMAT_RGB32F;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11881. /**
  11882. * RGBA32F
  11883. */
  11884. get: function () {
  11885. return Engine._TEXTUREFORMAT_RGBA32F;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11891. /** LUMINANCE_ALPHA */
  11892. get: function () {
  11893. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11899. /** RGB */
  11900. get: function () {
  11901. return Engine._TEXTUREFORMAT_RGB;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11907. /** RGBA */
  11908. get: function () {
  11909. return Engine._TEXTUREFORMAT_RGBA;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11915. /** UNSIGNED_INT */
  11916. get: function () {
  11917. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11923. /** FLOAT */
  11924. get: function () {
  11925. return Engine._TEXTURETYPE_FLOAT;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11931. /** HALF_FLOAT */
  11932. get: function () {
  11933. return Engine._TEXTURETYPE_HALF_FLOAT;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11939. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11940. get: function () {
  11941. return Engine._SCALEMODE_FLOOR;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11947. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11948. get: function () {
  11949. return Engine._SCALEMODE_NEAREST;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11955. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11956. get: function () {
  11957. return Engine._SCALEMODE_CEILING;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Object.defineProperty(Engine, "Version", {
  11963. /**
  11964. * Returns the current version of the framework
  11965. */
  11966. get: function () {
  11967. return "3.2.0-rc.4";
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11973. /**
  11974. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11975. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11976. */
  11977. get: function () {
  11978. return this._vrExclusivePointerMode;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11984. /**
  11985. * Gets a boolean indicating that the engine supports uniform buffers
  11986. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11987. */
  11988. get: function () {
  11989. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11995. /**
  11996. * Gets a boolean indicating that only power of 2 textures are supported
  11997. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11998. */
  11999. get: function () {
  12000. return this._webGLVersion < 2 || this.forcePOTTextures;
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12006. /**
  12007. * Gets the performance monitor attached to this engine
  12008. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12009. */
  12010. get: function () {
  12011. return this._performanceMonitor;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12017. /**
  12018. * Gets the list of texture formats supported
  12019. */
  12020. get: function () {
  12021. return this._texturesSupported;
  12022. },
  12023. enumerable: true,
  12024. configurable: true
  12025. });
  12026. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12027. /**
  12028. * Gets the list of texture formats in use
  12029. */
  12030. get: function () {
  12031. return this._textureFormatInUse;
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(Engine.prototype, "currentViewport", {
  12037. /**
  12038. * Gets the current viewport
  12039. */
  12040. get: function () {
  12041. return this._cachedViewport;
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12047. /**
  12048. * Gets the default empty texture
  12049. */
  12050. get: function () {
  12051. if (!this._emptyTexture) {
  12052. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12053. }
  12054. return this._emptyTexture;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12060. /**
  12061. * Gets the default empty 3D texture
  12062. */
  12063. get: function () {
  12064. if (!this._emptyTexture3D) {
  12065. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12066. }
  12067. return this._emptyTexture3D;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12073. /**
  12074. * Gets the default empty cube texture
  12075. */
  12076. get: function () {
  12077. if (!this._emptyCubeTexture) {
  12078. var faceData = new Uint8Array(4);
  12079. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12080. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12081. }
  12082. return this._emptyCubeTexture;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Engine.prototype._rebuildInternalTextures = function () {
  12088. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12089. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12090. var internalTexture = currentState_1[_i];
  12091. internalTexture._rebuild();
  12092. }
  12093. };
  12094. Engine.prototype._rebuildEffects = function () {
  12095. for (var key in this._compiledEffects) {
  12096. var effect = this._compiledEffects[key];
  12097. effect._prepareEffect();
  12098. }
  12099. BABYLON.Effect.ResetCache();
  12100. };
  12101. Engine.prototype._rebuildBuffers = function () {
  12102. // Index / Vertex
  12103. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12104. var scene = _a[_i];
  12105. scene.resetCachedMaterial();
  12106. scene._rebuildGeometries();
  12107. scene._rebuildTextures();
  12108. }
  12109. // Uniforms
  12110. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12111. var uniformBuffer = _c[_b];
  12112. uniformBuffer._rebuild();
  12113. }
  12114. };
  12115. Engine.prototype._initGLContext = function () {
  12116. // Caps
  12117. this._caps = new EngineCapabilities();
  12118. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12119. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12120. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12121. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12122. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12123. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12124. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12125. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12126. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12127. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12128. // Infos
  12129. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12130. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12131. if (rendererInfo != null) {
  12132. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12133. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12134. }
  12135. if (!this._glVendor) {
  12136. this._glVendor = "Unknown vendor";
  12137. }
  12138. if (!this._glRenderer) {
  12139. this._glRenderer = "Unknown renderer";
  12140. }
  12141. // Constants
  12142. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12143. if (this._gl.RGBA16F !== 0x881A) {
  12144. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12145. }
  12146. if (this._gl.RGBA32F !== 0x8814) {
  12147. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12148. }
  12149. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12150. this._gl.DEPTH24_STENCIL8 = 35056;
  12151. }
  12152. // Extensions
  12153. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12154. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12155. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12156. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12157. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12158. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12159. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12160. 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');
  12161. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12162. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12163. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12164. this._caps.highPrecisionShaderSupported = true;
  12165. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12166. if (this._caps.timerQuery) {
  12167. if (this._webGLVersion === 1) {
  12168. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12169. }
  12170. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12171. }
  12172. // Checks if some of the format renders first to allow the use of webgl inspector.
  12173. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12174. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12175. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12176. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12177. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12178. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12179. if (this._webGLVersion > 1) {
  12180. this._gl.HALF_FLOAT_OES = 0x140B;
  12181. }
  12182. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12183. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12184. // Draw buffers
  12185. if (this._webGLVersion > 1) {
  12186. this._caps.drawBuffersExtension = true;
  12187. }
  12188. else {
  12189. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12190. if (drawBuffersExtension !== null) {
  12191. this._caps.drawBuffersExtension = true;
  12192. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12193. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12194. for (var i = 0; i < 16; i++) {
  12195. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12196. }
  12197. }
  12198. else {
  12199. this._caps.drawBuffersExtension = false;
  12200. }
  12201. }
  12202. // Depth Texture
  12203. if (this._webGLVersion > 1) {
  12204. this._caps.depthTextureExtension = true;
  12205. }
  12206. else {
  12207. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12208. if (depthTextureExtension != null) {
  12209. this._caps.depthTextureExtension = true;
  12210. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12211. }
  12212. }
  12213. // Vertex array object
  12214. if (this._webGLVersion > 1) {
  12215. this._caps.vertexArrayObject = true;
  12216. }
  12217. else {
  12218. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12219. if (vertexArrayObjectExtension != null) {
  12220. this._caps.vertexArrayObject = true;
  12221. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12222. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12223. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12224. }
  12225. else {
  12226. this._caps.vertexArrayObject = false;
  12227. }
  12228. }
  12229. // Instances count
  12230. if (this._webGLVersion > 1) {
  12231. this._caps.instancedArrays = true;
  12232. }
  12233. else {
  12234. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12235. if (instanceExtension != null) {
  12236. this._caps.instancedArrays = true;
  12237. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12238. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12239. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12240. }
  12241. else {
  12242. this._caps.instancedArrays = false;
  12243. }
  12244. }
  12245. // Intelligently add supported compressed formats in order to check for.
  12246. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12247. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12248. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12249. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12250. if (this._caps.astc)
  12251. this.texturesSupported.push('-astc.ktx');
  12252. if (this._caps.s3tc)
  12253. this.texturesSupported.push('-dxt.ktx');
  12254. if (this._caps.pvrtc)
  12255. this.texturesSupported.push('-pvrtc.ktx');
  12256. if (this._caps.etc2)
  12257. this.texturesSupported.push('-etc2.ktx');
  12258. if (this._caps.etc1)
  12259. this.texturesSupported.push('-etc1.ktx');
  12260. if (this._gl.getShaderPrecisionFormat) {
  12261. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12262. if (highp) {
  12263. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12264. }
  12265. }
  12266. // Depth buffer
  12267. this.setDepthBuffer(true);
  12268. this.setDepthFunctionToLessOrEqual();
  12269. this.setDepthWrite(true);
  12270. // Texture maps
  12271. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12272. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12273. this._nextFreeTextureSlots.push(slot);
  12274. }
  12275. };
  12276. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12277. /**
  12278. * Gets version of the current webGL context
  12279. */
  12280. get: function () {
  12281. return this._webGLVersion;
  12282. },
  12283. enumerable: true,
  12284. configurable: true
  12285. });
  12286. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12287. /**
  12288. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12289. */
  12290. get: function () {
  12291. return this._isStencilEnable;
  12292. },
  12293. enumerable: true,
  12294. configurable: true
  12295. });
  12296. Engine.prototype._prepareWorkingCanvas = function () {
  12297. if (this._workingCanvas) {
  12298. return;
  12299. }
  12300. this._workingCanvas = document.createElement("canvas");
  12301. var context = this._workingCanvas.getContext("2d");
  12302. if (context) {
  12303. this._workingContext = context;
  12304. }
  12305. };
  12306. /**
  12307. * Reset the texture cache to empty state
  12308. */
  12309. Engine.prototype.resetTextureCache = function () {
  12310. for (var key in this._boundTexturesCache) {
  12311. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12312. continue;
  12313. }
  12314. var boundTexture = this._boundTexturesCache[key];
  12315. if (boundTexture) {
  12316. this._removeDesignatedSlot(boundTexture);
  12317. }
  12318. this._boundTexturesCache[key] = null;
  12319. }
  12320. if (!this.disableTextureBindingOptimization) {
  12321. this._nextFreeTextureSlots = [];
  12322. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12323. this._nextFreeTextureSlots.push(slot);
  12324. }
  12325. }
  12326. this._currentTextureChannel = -1;
  12327. };
  12328. /**
  12329. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12330. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12331. * @returns true if engine is in deterministic lock step mode
  12332. */
  12333. Engine.prototype.isDeterministicLockStep = function () {
  12334. return this._deterministicLockstep;
  12335. };
  12336. /**
  12337. * Gets the max steps when engine is running in deterministic lock step
  12338. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12339. * @returns the max steps
  12340. */
  12341. Engine.prototype.getLockstepMaxSteps = function () {
  12342. return this._lockstepMaxSteps;
  12343. };
  12344. /**
  12345. * Gets an object containing information about the current webGL context
  12346. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12347. */
  12348. Engine.prototype.getGlInfo = function () {
  12349. return {
  12350. vendor: this._glVendor,
  12351. renderer: this._glRenderer,
  12352. version: this._glVersion
  12353. };
  12354. };
  12355. /**
  12356. * Gets current aspect ratio
  12357. * @param camera defines the camera to use to get the aspect ratio
  12358. * @param useScreen defines if screen size must be used (or the current render target if any)
  12359. * @returns a number defining the aspect ratio
  12360. */
  12361. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12362. if (useScreen === void 0) { useScreen = false; }
  12363. var viewport = camera.viewport;
  12364. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12365. };
  12366. /**
  12367. * Gets the current render width
  12368. * @param useScreen defines if screen size must be used (or the current render target if any)
  12369. * @returns a number defining the current render width
  12370. */
  12371. Engine.prototype.getRenderWidth = function (useScreen) {
  12372. if (useScreen === void 0) { useScreen = false; }
  12373. if (!useScreen && this._currentRenderTarget) {
  12374. return this._currentRenderTarget.width;
  12375. }
  12376. return this._gl.drawingBufferWidth;
  12377. };
  12378. /**
  12379. * Gets the current render height
  12380. * @param useScreen defines if screen size must be used (or the current render target if any)
  12381. * @returns a number defining the current render height
  12382. */
  12383. Engine.prototype.getRenderHeight = function (useScreen) {
  12384. if (useScreen === void 0) { useScreen = false; }
  12385. if (!useScreen && this._currentRenderTarget) {
  12386. return this._currentRenderTarget.height;
  12387. }
  12388. return this._gl.drawingBufferHeight;
  12389. };
  12390. /**
  12391. * Gets the HTML canvas attached with the current webGL context
  12392. * @returns a HTML canvas
  12393. */
  12394. Engine.prototype.getRenderingCanvas = function () {
  12395. return this._renderingCanvas;
  12396. };
  12397. /**
  12398. * Gets the client rect of the HTML canvas attached with the current webGL context
  12399. * @returns a client rectanglee
  12400. */
  12401. Engine.prototype.getRenderingCanvasClientRect = function () {
  12402. if (!this._renderingCanvas) {
  12403. return null;
  12404. }
  12405. return this._renderingCanvas.getBoundingClientRect();
  12406. };
  12407. /**
  12408. * Defines the hardware scaling level.
  12409. * By default the hardware scaling level is computed from the window device ratio.
  12410. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12411. * @param level defines the level to use
  12412. */
  12413. Engine.prototype.setHardwareScalingLevel = function (level) {
  12414. this._hardwareScalingLevel = level;
  12415. this.resize();
  12416. };
  12417. /**
  12418. * Gets the current hardware scaling level.
  12419. * By default the hardware scaling level is computed from the window device ratio.
  12420. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12421. * @returns a number indicating the current hardware scaling level
  12422. */
  12423. Engine.prototype.getHardwareScalingLevel = function () {
  12424. return this._hardwareScalingLevel;
  12425. };
  12426. /**
  12427. * Gets the list of loaded textures
  12428. * @returns an array containing all loaded textures
  12429. */
  12430. Engine.prototype.getLoadedTexturesCache = function () {
  12431. return this._internalTexturesCache;
  12432. };
  12433. /**
  12434. * Gets the object containing all engine capabilities
  12435. * @returns the EngineCapabilities object
  12436. */
  12437. Engine.prototype.getCaps = function () {
  12438. return this._caps;
  12439. };
  12440. Object.defineProperty(Engine.prototype, "drawCalls", {
  12441. /** @hidden */
  12442. get: function () {
  12443. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12444. return 0;
  12445. },
  12446. enumerable: true,
  12447. configurable: true
  12448. });
  12449. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12450. /** @hidden */
  12451. get: function () {
  12452. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12453. return null;
  12454. },
  12455. enumerable: true,
  12456. configurable: true
  12457. });
  12458. /**
  12459. * Gets the current depth function
  12460. * @returns a number defining the depth function
  12461. */
  12462. Engine.prototype.getDepthFunction = function () {
  12463. return this._depthCullingState.depthFunc;
  12464. };
  12465. /**
  12466. * Sets the current depth function
  12467. * @param depthFunc defines the function to use
  12468. */
  12469. Engine.prototype.setDepthFunction = function (depthFunc) {
  12470. this._depthCullingState.depthFunc = depthFunc;
  12471. };
  12472. /**
  12473. * Sets the current depth function to GREATER
  12474. */
  12475. Engine.prototype.setDepthFunctionToGreater = function () {
  12476. this._depthCullingState.depthFunc = this._gl.GREATER;
  12477. };
  12478. /**
  12479. * Sets the current depth function to GEQUAL
  12480. */
  12481. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12482. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12483. };
  12484. /**
  12485. * Sets the current depth function to LESS
  12486. */
  12487. Engine.prototype.setDepthFunctionToLess = function () {
  12488. this._depthCullingState.depthFunc = this._gl.LESS;
  12489. };
  12490. /**
  12491. * Sets the current depth function to LEQUAL
  12492. */
  12493. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12494. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12495. };
  12496. /**
  12497. * Gets a boolean indicating if stencil buffer is enabled
  12498. * @returns the current stencil buffer state
  12499. */
  12500. Engine.prototype.getStencilBuffer = function () {
  12501. return this._stencilState.stencilTest;
  12502. };
  12503. /**
  12504. * Enable or disable the stencil buffer
  12505. * @param enable defines if the stencil buffer must be enabled or disabled
  12506. */
  12507. Engine.prototype.setStencilBuffer = function (enable) {
  12508. this._stencilState.stencilTest = enable;
  12509. };
  12510. /**
  12511. * Gets the current stencil mask
  12512. * @returns a number defining the new stencil mask to use
  12513. */
  12514. Engine.prototype.getStencilMask = function () {
  12515. return this._stencilState.stencilMask;
  12516. };
  12517. /**
  12518. * Sets the current stencil mask
  12519. * @param mask defines the new stencil mask to use
  12520. */
  12521. Engine.prototype.setStencilMask = function (mask) {
  12522. this._stencilState.stencilMask = mask;
  12523. };
  12524. /**
  12525. * Gets the current stencil function
  12526. * @returns a number defining the stencil function to use
  12527. */
  12528. Engine.prototype.getStencilFunction = function () {
  12529. return this._stencilState.stencilFunc;
  12530. };
  12531. /**
  12532. * Gets the current stencil reference value
  12533. * @returns a number defining the stencil reference value to use
  12534. */
  12535. Engine.prototype.getStencilFunctionReference = function () {
  12536. return this._stencilState.stencilFuncRef;
  12537. };
  12538. /**
  12539. * Gets the current stencil mask
  12540. * @returns a number defining the stencil mask to use
  12541. */
  12542. Engine.prototype.getStencilFunctionMask = function () {
  12543. return this._stencilState.stencilFuncMask;
  12544. };
  12545. /**
  12546. * Sets the current stencil function
  12547. * @param stencilFunc defines the new stencil function to use
  12548. */
  12549. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12550. this._stencilState.stencilFunc = stencilFunc;
  12551. };
  12552. /**
  12553. * Sets the current stencil reference
  12554. * @param reference defines the new stencil reference to use
  12555. */
  12556. Engine.prototype.setStencilFunctionReference = function (reference) {
  12557. this._stencilState.stencilFuncRef = reference;
  12558. };
  12559. /**
  12560. * Sets the current stencil mask
  12561. * @param mask defines the new stencil mask to use
  12562. */
  12563. Engine.prototype.setStencilFunctionMask = function (mask) {
  12564. this._stencilState.stencilFuncMask = mask;
  12565. };
  12566. /**
  12567. * Gets the current stencil operation when stencil fails
  12568. * @returns a number defining stencil operation to use when stencil fails
  12569. */
  12570. Engine.prototype.getStencilOperationFail = function () {
  12571. return this._stencilState.stencilOpStencilFail;
  12572. };
  12573. /**
  12574. * Gets the current stencil operation when depth fails
  12575. * @returns a number defining stencil operation to use when depth fails
  12576. */
  12577. Engine.prototype.getStencilOperationDepthFail = function () {
  12578. return this._stencilState.stencilOpDepthFail;
  12579. };
  12580. /**
  12581. * Gets the current stencil operation when stencil passes
  12582. * @returns a number defining stencil operation to use when stencil passes
  12583. */
  12584. Engine.prototype.getStencilOperationPass = function () {
  12585. return this._stencilState.stencilOpStencilDepthPass;
  12586. };
  12587. /**
  12588. * Sets the stencil operation to use when stencil fails
  12589. * @param operation defines the stencil operation to use when stencil fails
  12590. */
  12591. Engine.prototype.setStencilOperationFail = function (operation) {
  12592. this._stencilState.stencilOpStencilFail = operation;
  12593. };
  12594. /**
  12595. * Sets the stencil operation to use when depth fails
  12596. * @param operation defines the stencil operation to use when depth fails
  12597. */
  12598. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12599. this._stencilState.stencilOpDepthFail = operation;
  12600. };
  12601. /**
  12602. * Sets the stencil operation to use when stencil passes
  12603. * @param operation defines the stencil operation to use when stencil passes
  12604. */
  12605. Engine.prototype.setStencilOperationPass = function (operation) {
  12606. this._stencilState.stencilOpStencilDepthPass = operation;
  12607. };
  12608. /**
  12609. * Sets a boolean indicating if the dithering state is enabled or disabled
  12610. * @param value defines the dithering state
  12611. */
  12612. Engine.prototype.setDitheringState = function (value) {
  12613. if (value) {
  12614. this._gl.enable(this._gl.DITHER);
  12615. }
  12616. else {
  12617. this._gl.disable(this._gl.DITHER);
  12618. }
  12619. };
  12620. /**
  12621. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12622. * @param value defines the rasterizer state
  12623. */
  12624. Engine.prototype.setRasterizerState = function (value) {
  12625. if (value) {
  12626. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12627. }
  12628. else {
  12629. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12630. }
  12631. };
  12632. /**
  12633. * stop executing a render loop function and remove it from the execution array
  12634. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12635. */
  12636. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12637. if (!renderFunction) {
  12638. this._activeRenderLoops = [];
  12639. return;
  12640. }
  12641. var index = this._activeRenderLoops.indexOf(renderFunction);
  12642. if (index >= 0) {
  12643. this._activeRenderLoops.splice(index, 1);
  12644. }
  12645. };
  12646. /** @hidden */
  12647. Engine.prototype._renderLoop = function () {
  12648. if (!this._contextWasLost) {
  12649. var shouldRender = true;
  12650. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12651. shouldRender = false;
  12652. }
  12653. if (shouldRender) {
  12654. // Start new frame
  12655. this.beginFrame();
  12656. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12657. var renderFunction = this._activeRenderLoops[index];
  12658. renderFunction();
  12659. }
  12660. // Present
  12661. this.endFrame();
  12662. }
  12663. }
  12664. if (this._activeRenderLoops.length > 0) {
  12665. // Register new frame
  12666. var requester = null;
  12667. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12668. requester = this._vrDisplay;
  12669. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12670. }
  12671. else {
  12672. this._renderingQueueLaunched = false;
  12673. }
  12674. };
  12675. /**
  12676. * Register and execute a render loop. The engine can have more than one render function
  12677. * @param renderFunction defines the function to continuously execute
  12678. */
  12679. Engine.prototype.runRenderLoop = function (renderFunction) {
  12680. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12681. return;
  12682. }
  12683. this._activeRenderLoops.push(renderFunction);
  12684. if (!this._renderingQueueLaunched) {
  12685. this._renderingQueueLaunched = true;
  12686. this._bindedRenderFunction = this._renderLoop.bind(this);
  12687. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12688. }
  12689. };
  12690. /**
  12691. * Toggle full screen mode
  12692. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12693. * @param options defines an option object to be sent to the requestFullscreen function
  12694. */
  12695. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12696. if (this.isFullscreen) {
  12697. BABYLON.Tools.ExitFullscreen();
  12698. }
  12699. else {
  12700. this._pointerLockRequested = requestPointerLock;
  12701. if (this._renderingCanvas) {
  12702. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12703. }
  12704. }
  12705. };
  12706. /**
  12707. * Clear the current render buffer or the current render target (if any is set up)
  12708. * @param color defines the color to use
  12709. * @param backBuffer defines if the back buffer must be cleared
  12710. * @param depth defines if the depth buffer must be cleared
  12711. * @param stencil defines if the stencil buffer must be cleared
  12712. */
  12713. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12714. if (stencil === void 0) { stencil = false; }
  12715. this.applyStates();
  12716. var mode = 0;
  12717. if (backBuffer && color) {
  12718. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12719. mode |= this._gl.COLOR_BUFFER_BIT;
  12720. }
  12721. if (depth) {
  12722. this._gl.clearDepth(1.0);
  12723. mode |= this._gl.DEPTH_BUFFER_BIT;
  12724. }
  12725. if (stencil) {
  12726. this._gl.clearStencil(0);
  12727. mode |= this._gl.STENCIL_BUFFER_BIT;
  12728. }
  12729. this._gl.clear(mode);
  12730. };
  12731. /**
  12732. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12733. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12734. * @param y defines the y-coordinate of the corner of the clear rectangle
  12735. * @param width defines the width of the clear rectangle
  12736. * @param height defines the height of the clear rectangle
  12737. * @param clearColor defines the clear color
  12738. */
  12739. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12740. var gl = this._gl;
  12741. // Save state
  12742. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12743. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12744. // Change state
  12745. gl.enable(gl.SCISSOR_TEST);
  12746. gl.scissor(x, y, width, height);
  12747. // Clear
  12748. this.clear(clearColor, true, true, true);
  12749. // Restore state
  12750. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12751. if (curScissor === true) {
  12752. gl.enable(gl.SCISSOR_TEST);
  12753. }
  12754. else {
  12755. gl.disable(gl.SCISSOR_TEST);
  12756. }
  12757. };
  12758. /**
  12759. * Set the WebGL's viewport
  12760. * @param viewport defines the viewport element to be used
  12761. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12762. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12763. */
  12764. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12765. var width = requiredWidth || this.getRenderWidth();
  12766. var height = requiredHeight || this.getRenderHeight();
  12767. var x = viewport.x || 0;
  12768. var y = viewport.y || 0;
  12769. this._cachedViewport = viewport;
  12770. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12771. };
  12772. /**
  12773. * Directly set the WebGL Viewport
  12774. * @param x defines the x coordinate of the viewport (in screen space)
  12775. * @param y defines the y coordinate of the viewport (in screen space)
  12776. * @param width defines the width of the viewport (in screen space)
  12777. * @param height defines the height of the viewport (in screen space)
  12778. * @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
  12779. */
  12780. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12781. var currentViewport = this._cachedViewport;
  12782. this._cachedViewport = null;
  12783. this._gl.viewport(x, y, width, height);
  12784. return currentViewport;
  12785. };
  12786. /**
  12787. * Begin a new frame
  12788. */
  12789. Engine.prototype.beginFrame = function () {
  12790. this.onBeginFrameObservable.notifyObservers(this);
  12791. this._measureFps();
  12792. };
  12793. /**
  12794. * Enf the current frame
  12795. */
  12796. Engine.prototype.endFrame = function () {
  12797. // Force a flush in case we are using a bad OS.
  12798. if (this._badOS) {
  12799. this.flushFramebuffer();
  12800. }
  12801. // Submit frame to the vr device, if enabled
  12802. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12803. // TODO: We should only submit the frame if we read frameData successfully.
  12804. this._vrDisplay.submitFrame();
  12805. }
  12806. this.onEndFrameObservable.notifyObservers(this);
  12807. };
  12808. /**
  12809. * Resize the view according to the canvas' size
  12810. */
  12811. Engine.prototype.resize = function () {
  12812. // We're not resizing the size of the canvas while in VR mode & presenting
  12813. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12814. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12815. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12816. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12817. }
  12818. };
  12819. /**
  12820. * Force a specific size of the canvas
  12821. * @param width defines the new canvas' width
  12822. * @param height defines the new canvas' height
  12823. */
  12824. Engine.prototype.setSize = function (width, height) {
  12825. if (!this._renderingCanvas) {
  12826. return;
  12827. }
  12828. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12829. return;
  12830. }
  12831. this._renderingCanvas.width = width;
  12832. this._renderingCanvas.height = height;
  12833. for (var index = 0; index < this.scenes.length; index++) {
  12834. var scene = this.scenes[index];
  12835. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12836. var cam = scene.cameras[camIndex];
  12837. cam._currentRenderId = 0;
  12838. }
  12839. }
  12840. if (this.onResizeObservable.hasObservers) {
  12841. this.onResizeObservable.notifyObservers(this);
  12842. }
  12843. };
  12844. // WebVR functions
  12845. /**
  12846. * Gets a boolean indicating if a webVR device was detected
  12847. * @returns true if a webVR device was detected
  12848. */
  12849. Engine.prototype.isVRDevicePresent = function () {
  12850. return !!this._vrDisplay;
  12851. };
  12852. /**
  12853. * Gets the current webVR device
  12854. * @returns the current webVR device (or null)
  12855. */
  12856. Engine.prototype.getVRDevice = function () {
  12857. return this._vrDisplay;
  12858. };
  12859. /**
  12860. * Initializes a webVR display and starts listening to display change events
  12861. * The onVRDisplayChangedObservable will be notified upon these changes
  12862. * @returns The onVRDisplayChangedObservable
  12863. */
  12864. Engine.prototype.initWebVR = function () {
  12865. this.initWebVRAsync();
  12866. return this.onVRDisplayChangedObservable;
  12867. };
  12868. /**
  12869. * Initializes a webVR display and starts listening to display change events
  12870. * The onVRDisplayChangedObservable will be notified upon these changes
  12871. * @returns A promise containing a VRDisplay and if vr is supported
  12872. */
  12873. Engine.prototype.initWebVRAsync = function () {
  12874. var _this = this;
  12875. var notifyObservers = function () {
  12876. var eventArgs = {
  12877. vrDisplay: _this._vrDisplay,
  12878. vrSupported: _this._vrSupported
  12879. };
  12880. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12881. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12882. };
  12883. if (!this._onVrDisplayConnect) {
  12884. this._onVrDisplayConnect = function (event) {
  12885. _this._vrDisplay = event.display;
  12886. notifyObservers();
  12887. };
  12888. this._onVrDisplayDisconnect = function () {
  12889. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12890. _this._vrDisplay = undefined;
  12891. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12892. notifyObservers();
  12893. };
  12894. this._onVrDisplayPresentChange = function () {
  12895. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12896. };
  12897. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12898. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12899. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12900. }
  12901. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12902. this._webVRInitPromise.then(notifyObservers);
  12903. return this._webVRInitPromise;
  12904. };
  12905. /**
  12906. * Call this function to switch to webVR mode
  12907. * Will do nothing if webVR is not supported or if there is no webVR device
  12908. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12909. */
  12910. Engine.prototype.enableVR = function () {
  12911. var _this = this;
  12912. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12913. var onResolved = function () {
  12914. _this.onVRRequestPresentComplete.notifyObservers(true);
  12915. _this._onVRFullScreenTriggered();
  12916. };
  12917. var onRejected = function () {
  12918. _this.onVRRequestPresentComplete.notifyObservers(false);
  12919. };
  12920. this.onVRRequestPresentStart.notifyObservers(this);
  12921. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12922. }
  12923. };
  12924. /**
  12925. * Call this function to leave webVR mode
  12926. * Will do nothing if webVR is not supported or if there is no webVR device
  12927. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12928. */
  12929. Engine.prototype.disableVR = function () {
  12930. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12931. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12932. }
  12933. };
  12934. Engine.prototype._getVRDisplaysAsync = function () {
  12935. var _this = this;
  12936. return new Promise(function (res, rej) {
  12937. if (navigator.getVRDisplays) {
  12938. navigator.getVRDisplays().then(function (devices) {
  12939. _this._vrSupported = true;
  12940. // note that devices may actually be an empty array. This is fine;
  12941. // we expect this._vrDisplay to be undefined in this case.
  12942. _this._vrDisplay = devices[0];
  12943. res({
  12944. vrDisplay: _this._vrDisplay,
  12945. vrSupported: _this._vrSupported
  12946. });
  12947. });
  12948. }
  12949. else {
  12950. _this._vrDisplay = undefined;
  12951. _this._vrSupported = false;
  12952. res({
  12953. vrDisplay: _this._vrDisplay,
  12954. vrSupported: _this._vrSupported
  12955. });
  12956. }
  12957. });
  12958. };
  12959. /**
  12960. * Binds the frame buffer to the specified texture.
  12961. * @param texture The texture to render to or null for the default canvas
  12962. * @param faceIndex The face of the texture to render to in case of cube texture
  12963. * @param requiredWidth The width of the target to render to
  12964. * @param requiredHeight The height of the target to render to
  12965. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12966. * @param depthStencilTexture The depth stencil texture to use to render
  12967. */
  12968. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12969. if (this._currentRenderTarget) {
  12970. this.unBindFramebuffer(this._currentRenderTarget);
  12971. }
  12972. this._currentRenderTarget = texture;
  12973. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12974. var gl = this._gl;
  12975. if (texture.isCube) {
  12976. if (faceIndex === undefined) {
  12977. faceIndex = 0;
  12978. }
  12979. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12980. if (depthStencilTexture) {
  12981. if (depthStencilTexture._generateStencilBuffer) {
  12982. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12983. }
  12984. else {
  12985. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12986. }
  12987. }
  12988. }
  12989. if (this._cachedViewport && !forceFullscreenViewport) {
  12990. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12991. }
  12992. else {
  12993. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12994. }
  12995. this.wipeCaches();
  12996. };
  12997. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12998. if (this._currentFramebuffer !== framebuffer) {
  12999. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13000. this._currentFramebuffer = framebuffer;
  13001. }
  13002. };
  13003. /**
  13004. * Unbind the current render target texture from the webGL context
  13005. * @param texture defines the render target texture to unbind
  13006. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13007. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13008. */
  13009. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13010. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13011. this._currentRenderTarget = null;
  13012. // If MSAA, we need to bitblt back to main texture
  13013. var gl = this._gl;
  13014. if (texture._MSAAFramebuffer) {
  13015. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13016. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13017. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13018. }
  13019. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13020. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13021. gl.generateMipmap(gl.TEXTURE_2D);
  13022. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13023. }
  13024. if (onBeforeUnbind) {
  13025. if (texture._MSAAFramebuffer) {
  13026. // Bind the correct framebuffer
  13027. this.bindUnboundFramebuffer(texture._framebuffer);
  13028. }
  13029. onBeforeUnbind();
  13030. }
  13031. this.bindUnboundFramebuffer(null);
  13032. };
  13033. /**
  13034. * Unbind a list of render target textures from the webGL context
  13035. * This is used only when drawBuffer extension or webGL2 are active
  13036. * @param textures defines the render target textures to unbind
  13037. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13038. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13039. */
  13040. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13041. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13042. this._currentRenderTarget = null;
  13043. // If MSAA, we need to bitblt back to main texture
  13044. var gl = this._gl;
  13045. if (textures[0]._MSAAFramebuffer) {
  13046. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13047. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13048. var attachments = textures[0]._attachments;
  13049. if (!attachments) {
  13050. attachments = new Array(textures.length);
  13051. textures[0]._attachments = attachments;
  13052. }
  13053. for (var i = 0; i < textures.length; i++) {
  13054. var texture = textures[i];
  13055. for (var j = 0; j < attachments.length; j++) {
  13056. attachments[j] = gl.NONE;
  13057. }
  13058. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13059. gl.readBuffer(attachments[i]);
  13060. gl.drawBuffers(attachments);
  13061. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13062. }
  13063. for (var i = 0; i < attachments.length; i++) {
  13064. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13065. }
  13066. gl.drawBuffers(attachments);
  13067. }
  13068. for (var i = 0; i < textures.length; i++) {
  13069. var texture = textures[i];
  13070. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13071. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13072. gl.generateMipmap(gl.TEXTURE_2D);
  13073. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13074. }
  13075. }
  13076. if (onBeforeUnbind) {
  13077. if (textures[0]._MSAAFramebuffer) {
  13078. // Bind the correct framebuffer
  13079. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13080. }
  13081. onBeforeUnbind();
  13082. }
  13083. this.bindUnboundFramebuffer(null);
  13084. };
  13085. /**
  13086. * Force the mipmap generation for the given render target texture
  13087. * @param texture defines the render target texture to use
  13088. */
  13089. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13090. if (texture.generateMipMaps) {
  13091. var gl = this._gl;
  13092. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13093. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13094. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13095. }
  13096. };
  13097. /**
  13098. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13099. */
  13100. Engine.prototype.flushFramebuffer = function () {
  13101. this._gl.flush();
  13102. };
  13103. /**
  13104. * Unbind the current render target and bind the default framebuffer
  13105. */
  13106. Engine.prototype.restoreDefaultFramebuffer = function () {
  13107. if (this._currentRenderTarget) {
  13108. this.unBindFramebuffer(this._currentRenderTarget);
  13109. }
  13110. else {
  13111. this.bindUnboundFramebuffer(null);
  13112. }
  13113. if (this._cachedViewport) {
  13114. this.setViewport(this._cachedViewport);
  13115. }
  13116. this.wipeCaches();
  13117. };
  13118. // UBOs
  13119. /**
  13120. * Create an uniform buffer
  13121. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13122. * @param elements defines the content of the uniform buffer
  13123. * @returns the webGL uniform buffer
  13124. */
  13125. Engine.prototype.createUniformBuffer = function (elements) {
  13126. var ubo = this._gl.createBuffer();
  13127. if (!ubo) {
  13128. throw new Error("Unable to create uniform buffer");
  13129. }
  13130. this.bindUniformBuffer(ubo);
  13131. if (elements instanceof Float32Array) {
  13132. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13133. }
  13134. else {
  13135. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13136. }
  13137. this.bindUniformBuffer(null);
  13138. ubo.references = 1;
  13139. return ubo;
  13140. };
  13141. /**
  13142. * Create a dynamic uniform buffer
  13143. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13144. * @param elements defines the content of the uniform buffer
  13145. * @returns the webGL uniform buffer
  13146. */
  13147. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13148. var ubo = this._gl.createBuffer();
  13149. if (!ubo) {
  13150. throw new Error("Unable to create dynamic uniform buffer");
  13151. }
  13152. this.bindUniformBuffer(ubo);
  13153. if (elements instanceof Float32Array) {
  13154. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13155. }
  13156. else {
  13157. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13158. }
  13159. this.bindUniformBuffer(null);
  13160. ubo.references = 1;
  13161. return ubo;
  13162. };
  13163. /**
  13164. * Update an existing uniform buffer
  13165. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13166. * @param uniformBuffer defines the target uniform buffer
  13167. * @param elements defines the content to update
  13168. * @param offset defines the offset in the uniform buffer where update should start
  13169. * @param count defines the size of the data to update
  13170. */
  13171. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13172. this.bindUniformBuffer(uniformBuffer);
  13173. if (offset === undefined) {
  13174. offset = 0;
  13175. }
  13176. if (count === undefined) {
  13177. if (elements instanceof Float32Array) {
  13178. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13179. }
  13180. else {
  13181. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13182. }
  13183. }
  13184. else {
  13185. if (elements instanceof Float32Array) {
  13186. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13187. }
  13188. else {
  13189. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13190. }
  13191. }
  13192. this.bindUniformBuffer(null);
  13193. };
  13194. // VBOs
  13195. Engine.prototype._resetVertexBufferBinding = function () {
  13196. this.bindArrayBuffer(null);
  13197. this._cachedVertexBuffers = null;
  13198. };
  13199. /**
  13200. * Creates a vertex buffer
  13201. * @param data the data for the vertex buffer
  13202. * @returns the new WebGL static buffer
  13203. */
  13204. Engine.prototype.createVertexBuffer = function (data) {
  13205. var vbo = this._gl.createBuffer();
  13206. if (!vbo) {
  13207. throw new Error("Unable to create vertex buffer");
  13208. }
  13209. this.bindArrayBuffer(vbo);
  13210. if (data instanceof Array) {
  13211. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13212. }
  13213. else {
  13214. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13215. }
  13216. this._resetVertexBufferBinding();
  13217. vbo.references = 1;
  13218. return vbo;
  13219. };
  13220. /**
  13221. * Creates a dynamic vertex buffer
  13222. * @param data the data for the dynamic vertex buffer
  13223. * @returns the new WebGL dynamic buffer
  13224. */
  13225. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13226. var vbo = this._gl.createBuffer();
  13227. if (!vbo) {
  13228. throw new Error("Unable to create dynamic vertex buffer");
  13229. }
  13230. this.bindArrayBuffer(vbo);
  13231. if (data instanceof Array) {
  13232. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13233. }
  13234. else {
  13235. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13236. }
  13237. this._resetVertexBufferBinding();
  13238. vbo.references = 1;
  13239. return vbo;
  13240. };
  13241. /**
  13242. * Update a dynamic index buffer
  13243. * @param indexBuffer defines the target index buffer
  13244. * @param indices defines the data to update
  13245. * @param offset defines the offset in the target index buffer where update should start
  13246. */
  13247. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13248. if (offset === void 0) { offset = 0; }
  13249. // Force cache update
  13250. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13251. this.bindIndexBuffer(indexBuffer);
  13252. var arrayBuffer;
  13253. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13254. arrayBuffer = indices;
  13255. }
  13256. else {
  13257. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13258. }
  13259. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13260. this._resetIndexBufferBinding();
  13261. };
  13262. /**
  13263. * Updates a dynamic vertex buffer.
  13264. * @param vertexBuffer the vertex buffer to update
  13265. * @param data the data used to update the vertex buffer
  13266. * @param byteOffset the byte offset of the data
  13267. * @param byteLength the byte length of the data
  13268. */
  13269. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13270. this.bindArrayBuffer(vertexBuffer);
  13271. if (byteOffset === undefined) {
  13272. byteOffset = 0;
  13273. }
  13274. if (byteLength === undefined) {
  13275. if (data instanceof Array) {
  13276. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13277. }
  13278. else {
  13279. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13280. }
  13281. }
  13282. else {
  13283. if (data instanceof Array) {
  13284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13285. }
  13286. else {
  13287. if (data instanceof ArrayBuffer) {
  13288. data = new Uint8Array(data, byteOffset, byteLength);
  13289. }
  13290. else {
  13291. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13292. }
  13293. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13294. }
  13295. }
  13296. this._resetVertexBufferBinding();
  13297. };
  13298. Engine.prototype._resetIndexBufferBinding = function () {
  13299. this.bindIndexBuffer(null);
  13300. this._cachedIndexBuffer = null;
  13301. };
  13302. /**
  13303. * Creates a new index buffer
  13304. * @param indices defines the content of the index buffer
  13305. * @param updatable defines if the index buffer must be updatable
  13306. * @returns a new webGL buffer
  13307. */
  13308. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13309. var vbo = this._gl.createBuffer();
  13310. if (!vbo) {
  13311. throw new Error("Unable to create index buffer");
  13312. }
  13313. this.bindIndexBuffer(vbo);
  13314. // Check for 32 bits indices
  13315. var arrayBuffer;
  13316. var need32Bits = false;
  13317. if (indices instanceof Uint16Array) {
  13318. arrayBuffer = indices;
  13319. }
  13320. else {
  13321. //check 32 bit support
  13322. if (this._caps.uintIndices) {
  13323. if (indices instanceof Uint32Array) {
  13324. arrayBuffer = indices;
  13325. need32Bits = true;
  13326. }
  13327. else {
  13328. //number[] or Int32Array, check if 32 bit is necessary
  13329. for (var index = 0; index < indices.length; index++) {
  13330. if (indices[index] > 65535) {
  13331. need32Bits = true;
  13332. break;
  13333. }
  13334. }
  13335. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13336. }
  13337. }
  13338. else {
  13339. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13340. arrayBuffer = new Uint16Array(indices);
  13341. }
  13342. }
  13343. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13344. this._resetIndexBufferBinding();
  13345. vbo.references = 1;
  13346. vbo.is32Bits = need32Bits;
  13347. return vbo;
  13348. };
  13349. /**
  13350. * Bind a webGL buffer to the webGL context
  13351. * @param buffer defines the buffer to bind
  13352. */
  13353. Engine.prototype.bindArrayBuffer = function (buffer) {
  13354. if (!this._vaoRecordInProgress) {
  13355. this._unbindVertexArrayObject();
  13356. }
  13357. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13358. };
  13359. /**
  13360. * Bind an uniform buffer to the current webGL context
  13361. * @param buffer defines the buffer to bind
  13362. */
  13363. Engine.prototype.bindUniformBuffer = function (buffer) {
  13364. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13365. };
  13366. /**
  13367. * Bind a buffer to the current webGL context at a given location
  13368. * @param buffer defines the buffer to bind
  13369. * @param location defines the index where to bind the buffer
  13370. */
  13371. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13372. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13373. };
  13374. /**
  13375. * Bind a specific block at a given index in a specific shader program
  13376. * @param shaderProgram defines the shader program
  13377. * @param blockName defines the block name
  13378. * @param index defines the index where to bind the block
  13379. */
  13380. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13381. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13382. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13383. };
  13384. ;
  13385. Engine.prototype.bindIndexBuffer = function (buffer) {
  13386. if (!this._vaoRecordInProgress) {
  13387. this._unbindVertexArrayObject();
  13388. }
  13389. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13390. };
  13391. Engine.prototype.bindBuffer = function (buffer, target) {
  13392. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13393. this._gl.bindBuffer(target, buffer);
  13394. this._currentBoundBuffer[target] = buffer;
  13395. }
  13396. };
  13397. /**
  13398. * update the bound buffer with the given data
  13399. * @param data defines the data to update
  13400. */
  13401. Engine.prototype.updateArrayBuffer = function (data) {
  13402. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13403. };
  13404. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13405. var pointer = this._currentBufferPointers[indx];
  13406. var changed = false;
  13407. if (!pointer.active) {
  13408. changed = true;
  13409. pointer.active = true;
  13410. pointer.index = indx;
  13411. pointer.size = size;
  13412. pointer.type = type;
  13413. pointer.normalized = normalized;
  13414. pointer.stride = stride;
  13415. pointer.offset = offset;
  13416. pointer.buffer = buffer;
  13417. }
  13418. else {
  13419. if (pointer.buffer !== buffer) {
  13420. pointer.buffer = buffer;
  13421. changed = true;
  13422. }
  13423. if (pointer.size !== size) {
  13424. pointer.size = size;
  13425. changed = true;
  13426. }
  13427. if (pointer.type !== type) {
  13428. pointer.type = type;
  13429. changed = true;
  13430. }
  13431. if (pointer.normalized !== normalized) {
  13432. pointer.normalized = normalized;
  13433. changed = true;
  13434. }
  13435. if (pointer.stride !== stride) {
  13436. pointer.stride = stride;
  13437. changed = true;
  13438. }
  13439. if (pointer.offset !== offset) {
  13440. pointer.offset = offset;
  13441. changed = true;
  13442. }
  13443. }
  13444. if (changed || this._vaoRecordInProgress) {
  13445. this.bindArrayBuffer(buffer);
  13446. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13447. }
  13448. };
  13449. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13450. if (indexBuffer == null) {
  13451. return;
  13452. }
  13453. if (this._cachedIndexBuffer !== indexBuffer) {
  13454. this._cachedIndexBuffer = indexBuffer;
  13455. this.bindIndexBuffer(indexBuffer);
  13456. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13457. }
  13458. };
  13459. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13460. var attributes = effect.getAttributesNames();
  13461. if (!this._vaoRecordInProgress) {
  13462. this._unbindVertexArrayObject();
  13463. }
  13464. this.unbindAllAttributes();
  13465. for (var index = 0; index < attributes.length; index++) {
  13466. var order = effect.getAttributeLocation(index);
  13467. if (order >= 0) {
  13468. var vertexBuffer = vertexBuffers[attributes[index]];
  13469. if (!vertexBuffer) {
  13470. continue;
  13471. }
  13472. this._gl.enableVertexAttribArray(order);
  13473. if (!this._vaoRecordInProgress) {
  13474. this._vertexAttribArraysEnabled[order] = true;
  13475. }
  13476. var buffer = vertexBuffer.getBuffer();
  13477. if (buffer) {
  13478. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13479. if (vertexBuffer.getIsInstanced()) {
  13480. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13481. if (!this._vaoRecordInProgress) {
  13482. this._currentInstanceLocations.push(order);
  13483. this._currentInstanceBuffers.push(buffer);
  13484. }
  13485. }
  13486. }
  13487. }
  13488. }
  13489. };
  13490. /**
  13491. * Records a vertex array object
  13492. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13493. * @param vertexBuffers defines the list of vertex buffers to store
  13494. * @param indexBuffer defines the index buffer to store
  13495. * @param effect defines the effect to store
  13496. * @returns the new vertex array object
  13497. */
  13498. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13499. var vao = this._gl.createVertexArray();
  13500. this._vaoRecordInProgress = true;
  13501. this._gl.bindVertexArray(vao);
  13502. this._mustWipeVertexAttributes = true;
  13503. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13504. this.bindIndexBuffer(indexBuffer);
  13505. this._vaoRecordInProgress = false;
  13506. this._gl.bindVertexArray(null);
  13507. return vao;
  13508. };
  13509. /**
  13510. * Bind a specific vertex array object
  13511. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13512. * @param vertexArrayObject defines the vertex array object to bind
  13513. * @param indexBuffer defines the index buffer to bind
  13514. */
  13515. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13516. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13517. this._cachedVertexArrayObject = vertexArrayObject;
  13518. this._gl.bindVertexArray(vertexArrayObject);
  13519. this._cachedVertexBuffers = null;
  13520. this._cachedIndexBuffer = null;
  13521. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13522. this._mustWipeVertexAttributes = true;
  13523. }
  13524. };
  13525. /**
  13526. * Bind webGl buffers directly to the webGL context
  13527. * @param vertexBuffer defines the vertex buffer to bind
  13528. * @param indexBuffer defines the index buffer to bind
  13529. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13530. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13531. * @param effect defines the effect associated with the vertex buffer
  13532. */
  13533. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13534. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13535. this._cachedVertexBuffers = vertexBuffer;
  13536. this._cachedEffectForVertexBuffers = effect;
  13537. var attributesCount = effect.getAttributesCount();
  13538. this._unbindVertexArrayObject();
  13539. this.unbindAllAttributes();
  13540. var offset = 0;
  13541. for (var index = 0; index < attributesCount; index++) {
  13542. if (index < vertexDeclaration.length) {
  13543. var order = effect.getAttributeLocation(index);
  13544. if (order >= 0) {
  13545. this._gl.enableVertexAttribArray(order);
  13546. this._vertexAttribArraysEnabled[order] = true;
  13547. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13548. }
  13549. offset += vertexDeclaration[index] * 4;
  13550. }
  13551. }
  13552. }
  13553. this._bindIndexBufferWithCache(indexBuffer);
  13554. };
  13555. Engine.prototype._unbindVertexArrayObject = function () {
  13556. if (!this._cachedVertexArrayObject) {
  13557. return;
  13558. }
  13559. this._cachedVertexArrayObject = null;
  13560. this._gl.bindVertexArray(null);
  13561. };
  13562. /**
  13563. * Bind a list of vertex buffers to the webGL context
  13564. * @param vertexBuffers defines the list of vertex buffers to bind
  13565. * @param indexBuffer defines the index buffer to bind
  13566. * @param effect defines the effect associated with the vertex buffers
  13567. */
  13568. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13569. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13570. this._cachedVertexBuffers = vertexBuffers;
  13571. this._cachedEffectForVertexBuffers = effect;
  13572. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13573. }
  13574. this._bindIndexBufferWithCache(indexBuffer);
  13575. };
  13576. /**
  13577. * Unbind all instance attributes
  13578. */
  13579. Engine.prototype.unbindInstanceAttributes = function () {
  13580. var boundBuffer;
  13581. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13582. var instancesBuffer = this._currentInstanceBuffers[i];
  13583. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13584. boundBuffer = instancesBuffer;
  13585. this.bindArrayBuffer(instancesBuffer);
  13586. }
  13587. var offsetLocation = this._currentInstanceLocations[i];
  13588. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13589. }
  13590. this._currentInstanceBuffers.length = 0;
  13591. this._currentInstanceLocations.length = 0;
  13592. };
  13593. /**
  13594. * Release and free the memory of a vertex array object
  13595. * @param vao defines the vertex array object to delete
  13596. */
  13597. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13598. this._gl.deleteVertexArray(vao);
  13599. };
  13600. /** @hidden */
  13601. Engine.prototype._releaseBuffer = function (buffer) {
  13602. buffer.references--;
  13603. if (buffer.references === 0) {
  13604. this._gl.deleteBuffer(buffer);
  13605. return true;
  13606. }
  13607. return false;
  13608. };
  13609. /**
  13610. * Creates a webGL buffer to use with instanciation
  13611. * @param capacity defines the size of the buffer
  13612. * @returns the webGL buffer
  13613. */
  13614. Engine.prototype.createInstancesBuffer = function (capacity) {
  13615. var buffer = this._gl.createBuffer();
  13616. if (!buffer) {
  13617. throw new Error("Unable to create instance buffer");
  13618. }
  13619. buffer.capacity = capacity;
  13620. this.bindArrayBuffer(buffer);
  13621. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13622. return buffer;
  13623. };
  13624. /**
  13625. * Delete a webGL buffer used with instanciation
  13626. * @param buffer defines the webGL buffer to delete
  13627. */
  13628. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13629. this._gl.deleteBuffer(buffer);
  13630. };
  13631. /**
  13632. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13633. * @param instancesBuffer defines the webGL buffer to update and bind
  13634. * @param data defines the data to store in the buffer
  13635. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13636. */
  13637. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13638. this.bindArrayBuffer(instancesBuffer);
  13639. if (data) {
  13640. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13641. }
  13642. if (offsetLocations[0].index !== undefined) {
  13643. var stride = 0;
  13644. for (var i = 0; i < offsetLocations.length; i++) {
  13645. var ai = offsetLocations[i];
  13646. stride += ai.attributeSize * 4;
  13647. }
  13648. for (var i = 0; i < offsetLocations.length; i++) {
  13649. var ai = offsetLocations[i];
  13650. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13651. this._gl.enableVertexAttribArray(ai.index);
  13652. this._vertexAttribArraysEnabled[ai.index] = true;
  13653. }
  13654. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13655. this._gl.vertexAttribDivisor(ai.index, 1);
  13656. this._currentInstanceLocations.push(ai.index);
  13657. this._currentInstanceBuffers.push(instancesBuffer);
  13658. }
  13659. }
  13660. else {
  13661. for (var index = 0; index < 4; index++) {
  13662. var offsetLocation = offsetLocations[index];
  13663. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13664. this._gl.enableVertexAttribArray(offsetLocation);
  13665. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13666. }
  13667. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13668. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13669. this._currentInstanceLocations.push(offsetLocation);
  13670. this._currentInstanceBuffers.push(instancesBuffer);
  13671. }
  13672. }
  13673. };
  13674. /**
  13675. * Apply all cached states (depth, culling, stencil and alpha)
  13676. */
  13677. Engine.prototype.applyStates = function () {
  13678. this._depthCullingState.apply(this._gl);
  13679. this._stencilState.apply(this._gl);
  13680. this._alphaState.apply(this._gl);
  13681. };
  13682. /**
  13683. * Send a draw order
  13684. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13685. * @param indexStart defines the starting index
  13686. * @param indexCount defines the number of index to draw
  13687. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13688. */
  13689. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13690. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13691. };
  13692. /**
  13693. * Draw a list of points
  13694. * @param verticesStart defines the index of first vertex to draw
  13695. * @param verticesCount defines the count of vertices to draw
  13696. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13697. */
  13698. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13699. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13700. };
  13701. /**
  13702. * Draw a list of unindexed primitives
  13703. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13704. * @param verticesStart defines the index of first vertex to draw
  13705. * @param verticesCount defines the count of vertices to draw
  13706. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13707. */
  13708. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13709. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13710. };
  13711. /**
  13712. * Draw a list of indexed primitives
  13713. * @param fillMode defines the primitive to use
  13714. * @param indexStart defines the starting index
  13715. * @param indexCount defines the number of index to draw
  13716. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13717. */
  13718. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13719. // Apply states
  13720. this.applyStates();
  13721. this._drawCalls.addCount(1, false);
  13722. // Render
  13723. var drawMode = this._drawMode(fillMode);
  13724. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13725. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13726. if (instancesCount) {
  13727. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13728. }
  13729. else {
  13730. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13731. }
  13732. };
  13733. /**
  13734. * Draw a list of unindexed primitives
  13735. * @param fillMode defines the primitive to use
  13736. * @param verticesStart defines the index of first vertex to draw
  13737. * @param verticesCount defines the count of vertices to draw
  13738. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13739. */
  13740. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13741. // Apply states
  13742. this.applyStates();
  13743. this._drawCalls.addCount(1, false);
  13744. var drawMode = this._drawMode(fillMode);
  13745. if (instancesCount) {
  13746. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13747. }
  13748. else {
  13749. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13750. }
  13751. };
  13752. Engine.prototype._drawMode = function (fillMode) {
  13753. switch (fillMode) {
  13754. // Triangle views
  13755. case BABYLON.Material.TriangleFillMode:
  13756. return this._gl.TRIANGLES;
  13757. case BABYLON.Material.PointFillMode:
  13758. return this._gl.POINTS;
  13759. case BABYLON.Material.WireFrameFillMode:
  13760. return this._gl.LINES;
  13761. // Draw modes
  13762. case BABYLON.Material.PointListDrawMode:
  13763. return this._gl.POINTS;
  13764. case BABYLON.Material.LineListDrawMode:
  13765. return this._gl.LINES;
  13766. case BABYLON.Material.LineLoopDrawMode:
  13767. return this._gl.LINE_LOOP;
  13768. case BABYLON.Material.LineStripDrawMode:
  13769. return this._gl.LINE_STRIP;
  13770. case BABYLON.Material.TriangleStripDrawMode:
  13771. return this._gl.TRIANGLE_STRIP;
  13772. case BABYLON.Material.TriangleFanDrawMode:
  13773. return this._gl.TRIANGLE_FAN;
  13774. default:
  13775. return this._gl.TRIANGLES;
  13776. }
  13777. };
  13778. // Shaders
  13779. /** @hidden */
  13780. Engine.prototype._releaseEffect = function (effect) {
  13781. if (this._compiledEffects[effect._key]) {
  13782. delete this._compiledEffects[effect._key];
  13783. this._deleteProgram(effect.getProgram());
  13784. }
  13785. };
  13786. /** @hidden */
  13787. Engine.prototype._deleteProgram = function (program) {
  13788. if (program) {
  13789. program.__SPECTOR_rebuildProgram = null;
  13790. if (program.transformFeedback) {
  13791. this.deleteTransformFeedback(program.transformFeedback);
  13792. program.transformFeedback = null;
  13793. }
  13794. this._gl.deleteProgram(program);
  13795. }
  13796. };
  13797. /**
  13798. * Create a new effect (used to store vertex/fragment shaders)
  13799. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13800. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13801. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13802. * @param samplers defines an array of string used to represent textures
  13803. * @param defines defines the string containing the defines to use to compile the shaders
  13804. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13805. * @param onCompiled defines a function to call when the effect creation is successful
  13806. * @param onError defines a function to call when the effect creation has failed
  13807. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13808. * @returns the new Effect
  13809. */
  13810. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13811. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13812. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13813. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13814. if (this._compiledEffects[name]) {
  13815. var compiledEffect = this._compiledEffects[name];
  13816. if (onCompiled && compiledEffect.isReady()) {
  13817. onCompiled(compiledEffect);
  13818. }
  13819. return compiledEffect;
  13820. }
  13821. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13822. effect._key = name;
  13823. this._compiledEffects[name] = effect;
  13824. return effect;
  13825. };
  13826. /**
  13827. * Create an effect to use with particle systems
  13828. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13829. * @param uniformsNames defines a list of attribute names
  13830. * @param samplers defines an array of string used to represent textures
  13831. * @param defines defines the string containing the defines to use to compile the shaders
  13832. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13833. * @param onCompiled defines a function to call when the effect creation is successful
  13834. * @param onError defines a function to call when the effect creation has failed
  13835. * @returns the new Effect
  13836. */
  13837. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13838. if (uniformsNames === void 0) { uniformsNames = []; }
  13839. if (samplers === void 0) { samplers = []; }
  13840. if (defines === void 0) { defines = ""; }
  13841. return this.createEffect({
  13842. vertex: "particles",
  13843. fragmentElement: fragmentName
  13844. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13845. };
  13846. /**
  13847. * Directly creates a webGL program
  13848. * @param vertexCode defines the vertex shader code to use
  13849. * @param fragmentCode defines the fragment shader code to use
  13850. * @param context defines the webGL context to use (if not set, the current one will be used)
  13851. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13852. * @returns the new webGL program
  13853. */
  13854. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13855. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13856. context = context || this._gl;
  13857. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13858. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13859. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13860. };
  13861. /**
  13862. * Creates a webGL program
  13863. * @param vertexCode defines the vertex shader code to use
  13864. * @param fragmentCode defines the fragment shader code to use
  13865. * @param defines defines the string containing the defines to use to compile the shaders
  13866. * @param context defines the webGL context to use (if not set, the current one will be used)
  13867. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13868. * @returns the new webGL program
  13869. */
  13870. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13871. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13872. context = context || this._gl;
  13873. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13874. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13875. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13876. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13877. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13878. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13879. return program;
  13880. };
  13881. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13882. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13883. var shaderProgram = context.createProgram();
  13884. if (!shaderProgram) {
  13885. throw new Error("Unable to create program");
  13886. }
  13887. context.attachShader(shaderProgram, vertexShader);
  13888. context.attachShader(shaderProgram, fragmentShader);
  13889. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13890. var transformFeedback = this.createTransformFeedback();
  13891. this.bindTransformFeedback(transformFeedback);
  13892. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13893. shaderProgram.transformFeedback = transformFeedback;
  13894. }
  13895. context.linkProgram(shaderProgram);
  13896. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13897. this.bindTransformFeedback(null);
  13898. }
  13899. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13900. if (!linked) {
  13901. context.validateProgram(shaderProgram);
  13902. var error = context.getProgramInfoLog(shaderProgram);
  13903. if (error) {
  13904. throw new Error(error);
  13905. }
  13906. }
  13907. context.deleteShader(vertexShader);
  13908. context.deleteShader(fragmentShader);
  13909. return shaderProgram;
  13910. };
  13911. /**
  13912. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13913. * @param shaderProgram defines the webGL program to use
  13914. * @param uniformsNames defines the list of uniform names
  13915. * @returns an array of webGL uniform locations
  13916. */
  13917. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13918. var results = new Array();
  13919. for (var index = 0; index < uniformsNames.length; index++) {
  13920. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13921. }
  13922. return results;
  13923. };
  13924. /**
  13925. * Gets the lsit of active attributes for a given webGL program
  13926. * @param shaderProgram defines the webGL program to use
  13927. * @param attributesNames defines the list of attribute names to get
  13928. * @returns an array of indices indicating the offset of each attribute
  13929. */
  13930. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13931. var results = [];
  13932. for (var index = 0; index < attributesNames.length; index++) {
  13933. try {
  13934. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13935. }
  13936. catch (e) {
  13937. results.push(-1);
  13938. }
  13939. }
  13940. return results;
  13941. };
  13942. /**
  13943. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13944. * @param effect defines the effect to activate
  13945. */
  13946. Engine.prototype.enableEffect = function (effect) {
  13947. if (!effect) {
  13948. return;
  13949. }
  13950. // Use program
  13951. this.bindSamplers(effect);
  13952. this._currentEffect = effect;
  13953. if (effect.onBind) {
  13954. effect.onBind(effect);
  13955. }
  13956. effect.onBindObservable.notifyObservers(effect);
  13957. };
  13958. /**
  13959. * Set the value of an uniform to an array of int32
  13960. * @param uniform defines the webGL uniform location where to store the value
  13961. * @param array defines the array of int32 to store
  13962. */
  13963. Engine.prototype.setIntArray = function (uniform, array) {
  13964. if (!uniform)
  13965. return;
  13966. this._gl.uniform1iv(uniform, array);
  13967. };
  13968. /**
  13969. * Set the value of an uniform to an array of int32 (stored as vec2)
  13970. * @param uniform defines the webGL uniform location where to store the value
  13971. * @param array defines the array of int32 to store
  13972. */
  13973. Engine.prototype.setIntArray2 = function (uniform, array) {
  13974. if (!uniform || array.length % 2 !== 0)
  13975. return;
  13976. this._gl.uniform2iv(uniform, array);
  13977. };
  13978. /**
  13979. * Set the value of an uniform to an array of int32 (stored as vec3)
  13980. * @param uniform defines the webGL uniform location where to store the value
  13981. * @param array defines the array of int32 to store
  13982. */
  13983. Engine.prototype.setIntArray3 = function (uniform, array) {
  13984. if (!uniform || array.length % 3 !== 0)
  13985. return;
  13986. this._gl.uniform3iv(uniform, array);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to an array of int32 (stored as vec4)
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param array defines the array of int32 to store
  13992. */
  13993. Engine.prototype.setIntArray4 = function (uniform, array) {
  13994. if (!uniform || array.length % 4 !== 0)
  13995. return;
  13996. this._gl.uniform4iv(uniform, array);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to an array of float32
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param array defines the array of float32 to store
  14002. */
  14003. Engine.prototype.setFloatArray = function (uniform, array) {
  14004. if (!uniform)
  14005. return;
  14006. this._gl.uniform1fv(uniform, array);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to an array of float32 (stored as vec2)
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param array defines the array of float32 to store
  14012. */
  14013. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14014. if (!uniform || array.length % 2 !== 0)
  14015. return;
  14016. this._gl.uniform2fv(uniform, array);
  14017. };
  14018. /**
  14019. * Set the value of an uniform to an array of float32 (stored as vec3)
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param array defines the array of float32 to store
  14022. */
  14023. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14024. if (!uniform || array.length % 3 !== 0)
  14025. return;
  14026. this._gl.uniform3fv(uniform, array);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to an array of float32 (stored as vec4)
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param array defines the array of float32 to store
  14032. */
  14033. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14034. if (!uniform || array.length % 4 !== 0)
  14035. return;
  14036. this._gl.uniform4fv(uniform, array);
  14037. };
  14038. /**
  14039. * Set the value of an uniform to an array of number
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param array defines the array of number to store
  14042. */
  14043. Engine.prototype.setArray = function (uniform, array) {
  14044. if (!uniform)
  14045. return;
  14046. this._gl.uniform1fv(uniform, array);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to an array of number (stored as vec2)
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param array defines the array of number to store
  14052. */
  14053. Engine.prototype.setArray2 = function (uniform, array) {
  14054. if (!uniform || array.length % 2 !== 0)
  14055. return;
  14056. this._gl.uniform2fv(uniform, array);
  14057. };
  14058. /**
  14059. * Set the value of an uniform to an array of number (stored as vec3)
  14060. * @param uniform defines the webGL uniform location where to store the value
  14061. * @param array defines the array of number to store
  14062. */
  14063. Engine.prototype.setArray3 = function (uniform, array) {
  14064. if (!uniform || array.length % 3 !== 0)
  14065. return;
  14066. this._gl.uniform3fv(uniform, array);
  14067. };
  14068. /**
  14069. * Set the value of an uniform to an array of number (stored as vec4)
  14070. * @param uniform defines the webGL uniform location where to store the value
  14071. * @param array defines the array of number to store
  14072. */
  14073. Engine.prototype.setArray4 = function (uniform, array) {
  14074. if (!uniform || array.length % 4 !== 0)
  14075. return;
  14076. this._gl.uniform4fv(uniform, array);
  14077. };
  14078. /**
  14079. * Set the value of an uniform to an array of float32 (stored as matrices)
  14080. * @param uniform defines the webGL uniform location where to store the value
  14081. * @param matrices defines the array of float32 to store
  14082. */
  14083. Engine.prototype.setMatrices = function (uniform, matrices) {
  14084. if (!uniform)
  14085. return;
  14086. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14087. };
  14088. /**
  14089. * Set the value of an uniform to a matrix
  14090. * @param uniform defines the webGL uniform location where to store the value
  14091. * @param matrix defines the matrix to store
  14092. */
  14093. Engine.prototype.setMatrix = function (uniform, matrix) {
  14094. if (!uniform)
  14095. return;
  14096. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14097. };
  14098. /**
  14099. * Set the value of an uniform to a matrix (3x3)
  14100. * @param uniform defines the webGL uniform location where to store the value
  14101. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14102. */
  14103. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14104. if (!uniform)
  14105. return;
  14106. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14107. };
  14108. /**
  14109. * Set the value of an uniform to a matrix (2x2)
  14110. * @param uniform defines the webGL uniform location where to store the value
  14111. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14112. */
  14113. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14114. if (!uniform)
  14115. return;
  14116. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to a number (int)
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param value defines the int number to store
  14122. */
  14123. Engine.prototype.setInt = function (uniform, value) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniform1i(uniform, value);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to a number (float)
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param value defines the float number to store
  14132. */
  14133. Engine.prototype.setFloat = function (uniform, value) {
  14134. if (!uniform)
  14135. return;
  14136. this._gl.uniform1f(uniform, value);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to a vec2
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param x defines the 1st component of the value
  14142. * @param y defines the 2nd component of the value
  14143. */
  14144. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniform2f(uniform, x, y);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a vec3
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param x defines the 1st component of the value
  14153. * @param y defines the 2nd component of the value
  14154. * @param z defines the 3rd component of the value
  14155. */
  14156. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14157. if (!uniform)
  14158. return;
  14159. this._gl.uniform3f(uniform, x, y, z);
  14160. };
  14161. /**
  14162. * Set the value of an uniform to a boolean
  14163. * @param uniform defines the webGL uniform location where to store the value
  14164. * @param bool defines the boolean to store
  14165. */
  14166. Engine.prototype.setBool = function (uniform, bool) {
  14167. if (!uniform)
  14168. return;
  14169. this._gl.uniform1i(uniform, bool);
  14170. };
  14171. /**
  14172. * Set the value of an uniform to a vec4
  14173. * @param uniform defines the webGL uniform location where to store the value
  14174. * @param x defines the 1st component of the value
  14175. * @param y defines the 2nd component of the value
  14176. * @param z defines the 3rd component of the value
  14177. * @param w defines the 4th component of the value
  14178. */
  14179. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14180. if (!uniform)
  14181. return;
  14182. this._gl.uniform4f(uniform, x, y, z, w);
  14183. };
  14184. /**
  14185. * Set the value of an uniform to a Color3
  14186. * @param uniform defines the webGL uniform location where to store the value
  14187. * @param color3 defines the color to store
  14188. */
  14189. Engine.prototype.setColor3 = function (uniform, color3) {
  14190. if (!uniform)
  14191. return;
  14192. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14193. };
  14194. /**
  14195. * Set the value of an uniform to a Color3 and an alpha value
  14196. * @param uniform defines the webGL uniform location where to store the value
  14197. * @param color3 defines the color to store
  14198. * @param alpha defines the alpha component to store
  14199. */
  14200. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14201. if (!uniform)
  14202. return;
  14203. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14204. };
  14205. /**
  14206. * Sets a Color4 on a uniform variable
  14207. * @param uniform defines the uniform location
  14208. * @param color4 defines the value to be set
  14209. */
  14210. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14211. if (!uniform)
  14212. return;
  14213. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14214. };
  14215. // States
  14216. /**
  14217. * Set various states to the webGL context
  14218. * @param culling defines backface culling state
  14219. * @param zOffset defines the value to apply to zOffset (0 by default)
  14220. * @param force defines if states must be applied even if cache is up to date
  14221. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14222. */
  14223. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14224. if (zOffset === void 0) { zOffset = 0; }
  14225. if (reverseSide === void 0) { reverseSide = false; }
  14226. // Culling
  14227. if (this._depthCullingState.cull !== culling || force) {
  14228. this._depthCullingState.cull = culling;
  14229. }
  14230. // Cull face
  14231. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14232. if (this._depthCullingState.cullFace !== cullFace || force) {
  14233. this._depthCullingState.cullFace = cullFace;
  14234. }
  14235. // Z offset
  14236. this.setZOffset(zOffset);
  14237. // Front face
  14238. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14239. if (this._depthCullingState.frontFace !== frontFace || force) {
  14240. this._depthCullingState.frontFace = frontFace;
  14241. }
  14242. };
  14243. /**
  14244. * Set the z offset to apply to current rendering
  14245. * @param value defines the offset to apply
  14246. */
  14247. Engine.prototype.setZOffset = function (value) {
  14248. this._depthCullingState.zOffset = value;
  14249. };
  14250. /**
  14251. * Gets the current value of the zOffset
  14252. * @returns the current zOffset state
  14253. */
  14254. Engine.prototype.getZOffset = function () {
  14255. return this._depthCullingState.zOffset;
  14256. };
  14257. /**
  14258. * Enable or disable depth buffering
  14259. * @param enable defines the state to set
  14260. */
  14261. Engine.prototype.setDepthBuffer = function (enable) {
  14262. this._depthCullingState.depthTest = enable;
  14263. };
  14264. /**
  14265. * Gets a boolean indicating if depth writing is enabled
  14266. * @returns the current depth writing state
  14267. */
  14268. Engine.prototype.getDepthWrite = function () {
  14269. return this._depthCullingState.depthMask;
  14270. };
  14271. /**
  14272. * Enable or disable depth writing
  14273. * @param enable defines the state to set
  14274. */
  14275. Engine.prototype.setDepthWrite = function (enable) {
  14276. this._depthCullingState.depthMask = enable;
  14277. };
  14278. /**
  14279. * Enable or disable color writing
  14280. * @param enable defines the state to set
  14281. */
  14282. Engine.prototype.setColorWrite = function (enable) {
  14283. this._gl.colorMask(enable, enable, enable, enable);
  14284. this._colorWrite = enable;
  14285. };
  14286. /**
  14287. * Gets a boolean indicating if color writing is enabled
  14288. * @returns the current color writing state
  14289. */
  14290. Engine.prototype.getColorWrite = function () {
  14291. return this._colorWrite;
  14292. };
  14293. /**
  14294. * Sets alpha constants used by some alpha blending modes
  14295. * @param r defines the red component
  14296. * @param g defines the green component
  14297. * @param b defines the blue component
  14298. * @param a defines the alpha component
  14299. */
  14300. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14301. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14302. };
  14303. /**
  14304. * Sets the current alpha mode
  14305. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14306. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14307. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14308. */
  14309. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14310. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14311. if (this._alphaMode === mode) {
  14312. return;
  14313. }
  14314. switch (mode) {
  14315. case Engine.ALPHA_DISABLE:
  14316. this._alphaState.alphaBlend = false;
  14317. break;
  14318. case Engine.ALPHA_PREMULTIPLIED:
  14319. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14320. this._alphaState.alphaBlend = true;
  14321. break;
  14322. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14323. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14324. this._alphaState.alphaBlend = true;
  14325. break;
  14326. case Engine.ALPHA_COMBINE:
  14327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14328. this._alphaState.alphaBlend = true;
  14329. break;
  14330. case Engine.ALPHA_ONEONE:
  14331. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14332. this._alphaState.alphaBlend = true;
  14333. break;
  14334. case Engine.ALPHA_ADD:
  14335. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14336. this._alphaState.alphaBlend = true;
  14337. break;
  14338. case Engine.ALPHA_SUBTRACT:
  14339. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14340. this._alphaState.alphaBlend = true;
  14341. break;
  14342. case Engine.ALPHA_MULTIPLY:
  14343. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14344. this._alphaState.alphaBlend = true;
  14345. break;
  14346. case Engine.ALPHA_MAXIMIZED:
  14347. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14348. this._alphaState.alphaBlend = true;
  14349. break;
  14350. case Engine.ALPHA_INTERPOLATE:
  14351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14352. this._alphaState.alphaBlend = true;
  14353. break;
  14354. case Engine.ALPHA_SCREENMODE:
  14355. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14356. this._alphaState.alphaBlend = true;
  14357. break;
  14358. }
  14359. if (!noDepthWriteChange) {
  14360. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14361. }
  14362. this._alphaMode = mode;
  14363. };
  14364. /**
  14365. * Gets the current alpha mode
  14366. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14367. * @returns the current alpha mode
  14368. */
  14369. Engine.prototype.getAlphaMode = function () {
  14370. return this._alphaMode;
  14371. };
  14372. // Textures
  14373. /**
  14374. * Force the entire cache to be cleared
  14375. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14376. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14377. */
  14378. Engine.prototype.wipeCaches = function (bruteForce) {
  14379. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14380. return;
  14381. }
  14382. this._currentEffect = null;
  14383. if (bruteForce) {
  14384. this.resetTextureCache();
  14385. this._currentProgram = null;
  14386. this._stencilState.reset();
  14387. this._depthCullingState.reset();
  14388. this.setDepthFunctionToLessOrEqual();
  14389. this._alphaState.reset();
  14390. }
  14391. this._resetVertexBufferBinding();
  14392. this._cachedIndexBuffer = null;
  14393. this._cachedEffectForVertexBuffers = null;
  14394. this._unbindVertexArrayObject();
  14395. this.bindIndexBuffer(null);
  14396. };
  14397. /**
  14398. * Set the compressed texture format to use, based on the formats you have, and the formats
  14399. * supported by the hardware / browser.
  14400. *
  14401. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14402. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14403. * to API arguments needed to compressed textures. This puts the burden on the container
  14404. * generator to house the arcane code for determining these for current & future formats.
  14405. *
  14406. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14407. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14408. *
  14409. * Note: The result of this call is not taken into account when a texture is base64.
  14410. *
  14411. * @param formatsAvailable defines the list of those format families you have created
  14412. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14413. *
  14414. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14415. * @returns The extension selected.
  14416. */
  14417. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14418. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14419. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14420. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14421. return this._textureFormatInUse = this._texturesSupported[i];
  14422. }
  14423. }
  14424. }
  14425. // actively set format to nothing, to allow this to be called more than once
  14426. // and possibly fail the 2nd time
  14427. this._textureFormatInUse = null;
  14428. return null;
  14429. };
  14430. /** @hidden */
  14431. Engine.prototype._createTexture = function () {
  14432. var texture = this._gl.createTexture();
  14433. if (!texture) {
  14434. throw new Error("Unable to create texture");
  14435. }
  14436. return texture;
  14437. };
  14438. /**
  14439. * Usually called from BABYLON.Texture.ts.
  14440. * Passed information to create a WebGLTexture
  14441. * @param urlArg defines a value which contains one of the following:
  14442. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14443. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14444. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14445. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14446. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14447. * @param scene needed for loading to the correct scene
  14448. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14449. * @param onLoad optional callback to be called upon successful completion
  14450. * @param onError optional callback to be called upon failure
  14451. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14452. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14453. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14454. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14455. */
  14456. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14457. var _this = this;
  14458. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14459. if (onLoad === void 0) { onLoad = null; }
  14460. if (onError === void 0) { onError = null; }
  14461. if (buffer === void 0) { buffer = null; }
  14462. if (fallback === void 0) { fallback = null; }
  14463. if (format === void 0) { format = null; }
  14464. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14465. var fromData = url.substr(0, 5) === "data:";
  14466. var fromBlob = url.substr(0, 5) === "blob:";
  14467. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14468. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14469. // establish the file extension, if possible
  14470. var lastDot = url.lastIndexOf('.');
  14471. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14472. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14473. var isTGA = (extension.indexOf(".tga") === 0);
  14474. // determine if a ktx file should be substituted
  14475. var isKTX = false;
  14476. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14477. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14478. isKTX = true;
  14479. }
  14480. if (scene) {
  14481. scene._addPendingData(texture);
  14482. }
  14483. texture.url = url;
  14484. texture.generateMipMaps = !noMipmap;
  14485. texture.samplingMode = samplingMode;
  14486. texture.invertY = invertY;
  14487. if (!this._doNotHandleContextLost) {
  14488. // Keep a link to the buffer only if we plan to handle context lost
  14489. texture._buffer = buffer;
  14490. }
  14491. var onLoadObserver = null;
  14492. if (onLoad && !fallback) {
  14493. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14494. }
  14495. if (!fallback)
  14496. this._internalTexturesCache.push(texture);
  14497. var onerror = function (message, exception) {
  14498. if (scene) {
  14499. scene._removePendingData(texture);
  14500. }
  14501. if (onLoadObserver) {
  14502. texture.onLoadedObservable.remove(onLoadObserver);
  14503. }
  14504. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14505. if (isKTX) {
  14506. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14507. }
  14508. else if (BABYLON.Tools.UseFallbackTexture) {
  14509. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14510. }
  14511. if (onError) {
  14512. onError(message || "Unknown error", exception);
  14513. }
  14514. };
  14515. var callback = null;
  14516. // processing for non-image formats
  14517. if (isKTX || isTGA || isDDS) {
  14518. if (isKTX) {
  14519. callback = function (data) {
  14520. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14521. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14522. ktx.uploadLevels(_this._gl, !noMipmap);
  14523. return false;
  14524. }, samplingMode);
  14525. };
  14526. }
  14527. else if (isTGA) {
  14528. callback = function (arrayBuffer) {
  14529. var data = new Uint8Array(arrayBuffer);
  14530. var header = BABYLON.TGATools.GetTGAHeader(data);
  14531. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14532. BABYLON.TGATools.UploadContent(_this._gl, data);
  14533. return false;
  14534. }, samplingMode);
  14535. };
  14536. }
  14537. else if (isDDS) {
  14538. callback = function (data) {
  14539. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14540. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14541. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14542. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14543. return false;
  14544. }, samplingMode);
  14545. };
  14546. }
  14547. if (!buffer) {
  14548. this._loadFile(url, function (data) {
  14549. if (callback) {
  14550. callback(data);
  14551. }
  14552. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14553. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14554. });
  14555. }
  14556. else {
  14557. if (callback) {
  14558. callback(buffer);
  14559. }
  14560. }
  14561. // image format processing
  14562. }
  14563. else {
  14564. var onload = function (img) {
  14565. if (fromBlob && !_this._doNotHandleContextLost) {
  14566. // We need to store the image if we need to rebuild the texture
  14567. // in case of a webgl context lost
  14568. texture._buffer = img;
  14569. }
  14570. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14571. var gl = _this._gl;
  14572. var isPot = (img.width === potWidth && img.height === potHeight);
  14573. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14574. if (isPot) {
  14575. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14576. return false;
  14577. }
  14578. // Using shaders to rescale because canvas.drawImage is lossy
  14579. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14580. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14581. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14583. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14584. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14586. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14587. _this._releaseTexture(source);
  14588. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14589. continuationCallback();
  14590. });
  14591. return true;
  14592. }, samplingMode);
  14593. };
  14594. if (!fromData || isBase64)
  14595. if (buffer instanceof HTMLImageElement) {
  14596. onload(buffer);
  14597. }
  14598. else {
  14599. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14600. }
  14601. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14602. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14603. else
  14604. onload(buffer);
  14605. }
  14606. return texture;
  14607. };
  14608. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14609. var _this = this;
  14610. var rtt = this.createRenderTargetTexture({
  14611. width: destination.width,
  14612. height: destination.height,
  14613. }, {
  14614. generateMipMaps: false,
  14615. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14616. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14617. generateDepthBuffer: false,
  14618. generateStencilBuffer: false
  14619. });
  14620. if (!this._rescalePostProcess) {
  14621. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14622. }
  14623. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14624. _this._rescalePostProcess.onApply = function (effect) {
  14625. effect._bindTexture("textureSampler", source);
  14626. };
  14627. var hostingScene = scene;
  14628. if (!hostingScene) {
  14629. hostingScene = _this.scenes[_this.scenes.length - 1];
  14630. }
  14631. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14632. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14633. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14634. _this.unBindFramebuffer(rtt);
  14635. _this._releaseTexture(rtt);
  14636. if (onComplete) {
  14637. onComplete();
  14638. }
  14639. });
  14640. };
  14641. /**
  14642. * Update a raw texture
  14643. * @param texture defines the texture to update
  14644. * @param data defines the data to store in the texture
  14645. * @param format defines the format of the data
  14646. * @param invertY defines if data must be stored with Y axis inverted
  14647. * @param compression defines the compression used (null by default)
  14648. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14649. */
  14650. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14651. if (compression === void 0) { compression = null; }
  14652. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14653. if (!texture) {
  14654. return;
  14655. }
  14656. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14657. var internalFormat = this._getInternalFormat(format);
  14658. var textureType = this._getWebGLTextureType(type);
  14659. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14660. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14661. if (!this._doNotHandleContextLost) {
  14662. texture._bufferView = data;
  14663. texture.format = format;
  14664. texture.type = type;
  14665. texture.invertY = invertY;
  14666. texture._compression = compression;
  14667. }
  14668. if (texture.width % 4 !== 0) {
  14669. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14670. }
  14671. if (compression && data) {
  14672. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14673. }
  14674. else {
  14675. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14676. }
  14677. if (texture.generateMipMaps) {
  14678. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14679. }
  14680. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14681. // this.resetTextureCache();
  14682. texture.isReady = true;
  14683. };
  14684. /**
  14685. * Creates a raw texture
  14686. * @param data defines the data to store in the texture
  14687. * @param width defines the width of the texture
  14688. * @param height defines the height of the texture
  14689. * @param format defines the format of the data
  14690. * @param generateMipMaps defines if the engine should generate the mip levels
  14691. * @param invertY defines if data must be stored with Y axis inverted
  14692. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14693. * @param compression defines the compression used (null by default)
  14694. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14695. * @returns the raw texture inside an InternalTexture
  14696. */
  14697. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14698. if (compression === void 0) { compression = null; }
  14699. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14700. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14701. texture.baseWidth = width;
  14702. texture.baseHeight = height;
  14703. texture.width = width;
  14704. texture.height = height;
  14705. texture.format = format;
  14706. texture.generateMipMaps = generateMipMaps;
  14707. texture.samplingMode = samplingMode;
  14708. texture.invertY = invertY;
  14709. texture._compression = compression;
  14710. texture.type = type;
  14711. if (!this._doNotHandleContextLost) {
  14712. texture._bufferView = data;
  14713. }
  14714. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14716. // Filters
  14717. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14718. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14719. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14720. if (generateMipMaps) {
  14721. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14722. }
  14723. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14724. this._internalTexturesCache.push(texture);
  14725. return texture;
  14726. };
  14727. /**
  14728. * Creates a dynamic texture
  14729. * @param width defines the width of the texture
  14730. * @param height defines the height of the texture
  14731. * @param generateMipMaps defines if the engine should generate the mip levels
  14732. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14733. * @returns the dynamic texture inside an InternalTexture
  14734. */
  14735. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14736. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14737. texture.baseWidth = width;
  14738. texture.baseHeight = height;
  14739. if (generateMipMaps) {
  14740. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14741. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14742. }
  14743. // this.resetTextureCache();
  14744. texture.width = width;
  14745. texture.height = height;
  14746. texture.isReady = false;
  14747. texture.generateMipMaps = generateMipMaps;
  14748. texture.samplingMode = samplingMode;
  14749. this.updateTextureSamplingMode(samplingMode, texture);
  14750. this._internalTexturesCache.push(texture);
  14751. return texture;
  14752. };
  14753. /**
  14754. * Update the sampling mode of a given texture
  14755. * @param samplingMode defines the required sampling mode
  14756. * @param texture defines the texture to update
  14757. */
  14758. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14759. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14760. if (texture.isCube) {
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14762. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14763. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14764. }
  14765. else if (texture.is3D) {
  14766. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14767. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14768. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14769. }
  14770. else {
  14771. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14772. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14774. }
  14775. texture.samplingMode = samplingMode;
  14776. };
  14777. /**
  14778. * Update the content of a dynamic texture
  14779. * @param texture defines the texture to update
  14780. * @param canvas defines the canvas containing the source
  14781. * @param invertY defines if data must be stored with Y axis inverted
  14782. * @param premulAlpha defines if alpha is stored as premultiplied
  14783. * @param format defines the format of the data
  14784. */
  14785. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14786. if (premulAlpha === void 0) { premulAlpha = false; }
  14787. if (!texture) {
  14788. return;
  14789. }
  14790. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14791. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14792. if (premulAlpha) {
  14793. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14794. }
  14795. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14796. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14797. if (texture.generateMipMaps) {
  14798. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14799. }
  14800. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14801. if (premulAlpha) {
  14802. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14803. }
  14804. texture.isReady = true;
  14805. };
  14806. /**
  14807. * Update a video texture
  14808. * @param texture defines the texture to update
  14809. * @param video defines the video element to use
  14810. * @param invertY defines if data must be stored with Y axis inverted
  14811. */
  14812. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14813. if (!texture || texture._isDisabled) {
  14814. return;
  14815. }
  14816. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14817. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14818. try {
  14819. // Testing video texture support
  14820. if (this._videoTextureSupported === undefined) {
  14821. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14822. if (this._gl.getError() !== 0) {
  14823. this._videoTextureSupported = false;
  14824. }
  14825. else {
  14826. this._videoTextureSupported = true;
  14827. }
  14828. }
  14829. // Copy video through the current working canvas if video texture is not supported
  14830. if (!this._videoTextureSupported) {
  14831. if (!texture._workingCanvas) {
  14832. texture._workingCanvas = document.createElement("canvas");
  14833. var context = texture._workingCanvas.getContext("2d");
  14834. if (!context) {
  14835. throw new Error("Unable to get 2d context");
  14836. }
  14837. texture._workingContext = context;
  14838. texture._workingCanvas.width = texture.width;
  14839. texture._workingCanvas.height = texture.height;
  14840. }
  14841. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14842. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14843. }
  14844. else {
  14845. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14846. }
  14847. if (texture.generateMipMaps) {
  14848. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14849. }
  14850. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14851. // this.resetTextureCache();
  14852. texture.isReady = true;
  14853. }
  14854. catch (ex) {
  14855. // Something unexpected
  14856. // Let's disable the texture
  14857. texture._isDisabled = true;
  14858. }
  14859. };
  14860. /**
  14861. * Updates a depth texture Comparison Mode and Function.
  14862. * If the comparison Function is equal to 0, the mode will be set to none.
  14863. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14864. * @param texture The texture to set the comparison function for
  14865. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14866. */
  14867. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14868. if (this.webGLVersion === 1) {
  14869. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14870. return;
  14871. }
  14872. var gl = this._gl;
  14873. if (texture.isCube) {
  14874. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14875. if (comparisonFunction === 0) {
  14876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14878. }
  14879. else {
  14880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14882. }
  14883. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14884. }
  14885. else {
  14886. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14887. if (comparisonFunction === 0) {
  14888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14890. }
  14891. else {
  14892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14894. }
  14895. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14896. }
  14897. texture._comparisonFunction = comparisonFunction;
  14898. };
  14899. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14900. var width = size.width || size;
  14901. var height = size.height || size;
  14902. internalTexture.baseWidth = width;
  14903. internalTexture.baseHeight = height;
  14904. internalTexture.width = width;
  14905. internalTexture.height = height;
  14906. internalTexture.isReady = true;
  14907. internalTexture.samples = 1;
  14908. internalTexture.generateMipMaps = false;
  14909. internalTexture._generateDepthBuffer = true;
  14910. internalTexture._generateStencilBuffer = generateStencil;
  14911. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14912. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14913. internalTexture._comparisonFunction = comparisonFunction;
  14914. var gl = this._gl;
  14915. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14916. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14917. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14918. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14919. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14920. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14921. if (comparisonFunction === 0) {
  14922. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14923. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14924. }
  14925. else {
  14926. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14927. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14928. }
  14929. };
  14930. /**
  14931. * Creates a depth stencil texture.
  14932. * This is only available in WebGL 2 or with the depth texture extension available.
  14933. * @param size The size of face edge in the texture.
  14934. * @param options The options defining the texture.
  14935. * @returns The texture
  14936. */
  14937. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14938. if (options.isCube) {
  14939. var width = size.width || size;
  14940. return this._createDepthStencilCubeTexture(width, options);
  14941. }
  14942. else {
  14943. return this._createDepthStencilTexture(size, options);
  14944. }
  14945. };
  14946. /**
  14947. * Creates a depth stencil texture.
  14948. * This is only available in WebGL 2 or with the depth texture extension available.
  14949. * @param size The size of face edge in the texture.
  14950. * @param options The options defining the texture.
  14951. * @returns The texture
  14952. */
  14953. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14954. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14955. if (!this._caps.depthTextureExtension) {
  14956. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14957. return internalTexture;
  14958. }
  14959. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14960. var gl = this._gl;
  14961. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14962. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14963. if (this.webGLVersion > 1) {
  14964. if (internalOptions.generateStencil) {
  14965. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14966. }
  14967. else {
  14968. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14969. }
  14970. }
  14971. else {
  14972. if (internalOptions.generateStencil) {
  14973. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14974. }
  14975. else {
  14976. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14977. }
  14978. }
  14979. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14980. return internalTexture;
  14981. };
  14982. /**
  14983. * Creates a depth stencil cube texture.
  14984. * This is only available in WebGL 2.
  14985. * @param size The size of face edge in the cube texture.
  14986. * @param options The options defining the cube texture.
  14987. * @returns The cube texture
  14988. */
  14989. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14990. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14991. internalTexture.isCube = true;
  14992. if (this.webGLVersion === 1) {
  14993. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14994. return internalTexture;
  14995. }
  14996. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14997. var gl = this._gl;
  14998. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14999. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15000. // Create the depth/stencil buffer
  15001. for (var face = 0; face < 6; face++) {
  15002. if (internalOptions.generateStencil) {
  15003. 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);
  15004. }
  15005. else {
  15006. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15007. }
  15008. }
  15009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15010. return internalTexture;
  15011. };
  15012. /**
  15013. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15014. * @param renderTarget The render target to set the frame buffer for
  15015. */
  15016. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15017. // Create the framebuffer
  15018. var internalTexture = renderTarget.getInternalTexture();
  15019. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15020. return;
  15021. }
  15022. var gl = this._gl;
  15023. var depthStencilTexture = renderTarget.depthStencilTexture;
  15024. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15025. if (depthStencilTexture.isCube) {
  15026. if (depthStencilTexture._generateStencilBuffer) {
  15027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15028. }
  15029. else {
  15030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15031. }
  15032. }
  15033. else {
  15034. if (depthStencilTexture._generateStencilBuffer) {
  15035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15036. }
  15037. else {
  15038. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15039. }
  15040. }
  15041. this.bindUnboundFramebuffer(null);
  15042. };
  15043. /**
  15044. * Creates a new render target texture
  15045. * @param size defines the size of the texture
  15046. * @param options defines the options used to create the texture
  15047. * @returns a new render target texture stored in an InternalTexture
  15048. */
  15049. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15050. var fullOptions = new RenderTargetCreationOptions();
  15051. if (options !== undefined && typeof options === "object") {
  15052. fullOptions.generateMipMaps = options.generateMipMaps;
  15053. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15054. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15055. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15056. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15057. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15058. }
  15059. else {
  15060. fullOptions.generateMipMaps = options;
  15061. fullOptions.generateDepthBuffer = true;
  15062. fullOptions.generateStencilBuffer = false;
  15063. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15064. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15065. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15066. }
  15067. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15068. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15069. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15070. }
  15071. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15072. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15073. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15074. }
  15075. var gl = this._gl;
  15076. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15077. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15078. var width = size.width || size;
  15079. var height = size.height || size;
  15080. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15081. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15082. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15083. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15084. }
  15085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15086. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15089. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15090. // Create the framebuffer
  15091. var framebuffer = gl.createFramebuffer();
  15092. this.bindUnboundFramebuffer(framebuffer);
  15093. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15094. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15095. if (fullOptions.generateMipMaps) {
  15096. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15097. }
  15098. // Unbind
  15099. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15100. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15101. this.bindUnboundFramebuffer(null);
  15102. texture._framebuffer = framebuffer;
  15103. texture.baseWidth = width;
  15104. texture.baseHeight = height;
  15105. texture.width = width;
  15106. texture.height = height;
  15107. texture.isReady = true;
  15108. texture.samples = 1;
  15109. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15110. texture.samplingMode = fullOptions.samplingMode;
  15111. texture.type = fullOptions.type;
  15112. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15113. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15114. // this.resetTextureCache();
  15115. this._internalTexturesCache.push(texture);
  15116. return texture;
  15117. };
  15118. /**
  15119. * Create a multi render target texture
  15120. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15121. * @param size defines the size of the texture
  15122. * @param options defines the creation options
  15123. * @returns the cube texture as an InternalTexture
  15124. */
  15125. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15126. var generateMipMaps = false;
  15127. var generateDepthBuffer = true;
  15128. var generateStencilBuffer = false;
  15129. var generateDepthTexture = false;
  15130. var textureCount = 1;
  15131. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15132. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15133. var types = new Array();
  15134. var samplingModes = new Array();
  15135. if (options !== undefined) {
  15136. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15137. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15138. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15139. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15140. textureCount = options.textureCount || 1;
  15141. if (options.types) {
  15142. types = options.types;
  15143. }
  15144. if (options.samplingModes) {
  15145. samplingModes = options.samplingModes;
  15146. }
  15147. }
  15148. var gl = this._gl;
  15149. // Create the framebuffer
  15150. var framebuffer = gl.createFramebuffer();
  15151. this.bindUnboundFramebuffer(framebuffer);
  15152. var width = size.width || size;
  15153. var height = size.height || size;
  15154. var textures = [];
  15155. var attachments = [];
  15156. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15157. for (var i = 0; i < textureCount; i++) {
  15158. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15159. var type = types[i] || defaultType;
  15160. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15161. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15162. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15163. }
  15164. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15165. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15166. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15167. }
  15168. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15169. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15170. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15171. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15172. }
  15173. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15174. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15175. textures.push(texture);
  15176. attachments.push(attachment);
  15177. gl.activeTexture(gl["TEXTURE" + i]);
  15178. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15181. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15183. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15184. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15185. if (generateMipMaps) {
  15186. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15187. }
  15188. // Unbind
  15189. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15190. texture._framebuffer = framebuffer;
  15191. texture._depthStencilBuffer = depthStencilBuffer;
  15192. texture.baseWidth = width;
  15193. texture.baseHeight = height;
  15194. texture.width = width;
  15195. texture.height = height;
  15196. texture.isReady = true;
  15197. texture.samples = 1;
  15198. texture.generateMipMaps = generateMipMaps;
  15199. texture.samplingMode = samplingMode;
  15200. texture.type = type;
  15201. texture._generateDepthBuffer = generateDepthBuffer;
  15202. texture._generateStencilBuffer = generateStencilBuffer;
  15203. texture._attachments = attachments;
  15204. this._internalTexturesCache.push(texture);
  15205. }
  15206. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15207. // Depth texture
  15208. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15209. gl.activeTexture(gl.TEXTURE0);
  15210. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15215. 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);
  15216. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15217. depthTexture._framebuffer = framebuffer;
  15218. depthTexture.baseWidth = width;
  15219. depthTexture.baseHeight = height;
  15220. depthTexture.width = width;
  15221. depthTexture.height = height;
  15222. depthTexture.isReady = true;
  15223. depthTexture.samples = 1;
  15224. depthTexture.generateMipMaps = generateMipMaps;
  15225. depthTexture.samplingMode = gl.NEAREST;
  15226. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15227. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15228. textures.push(depthTexture);
  15229. this._internalTexturesCache.push(depthTexture);
  15230. }
  15231. gl.drawBuffers(attachments);
  15232. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15233. this.bindUnboundFramebuffer(null);
  15234. this.resetTextureCache();
  15235. return textures;
  15236. };
  15237. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15238. if (samples === void 0) { samples = 1; }
  15239. var depthStencilBuffer = null;
  15240. var gl = this._gl;
  15241. // Create the depth/stencil buffer
  15242. if (generateStencilBuffer) {
  15243. depthStencilBuffer = gl.createRenderbuffer();
  15244. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15245. if (samples > 1) {
  15246. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15247. }
  15248. else {
  15249. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15250. }
  15251. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15252. }
  15253. else if (generateDepthBuffer) {
  15254. depthStencilBuffer = gl.createRenderbuffer();
  15255. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15256. if (samples > 1) {
  15257. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15258. }
  15259. else {
  15260. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15261. }
  15262. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15263. }
  15264. return depthStencilBuffer;
  15265. };
  15266. /**
  15267. * Updates the sample count of a render target texture
  15268. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15269. * @param texture defines the texture to update
  15270. * @param samples defines the sample count to set
  15271. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15272. */
  15273. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15274. if (this.webGLVersion < 2 || !texture) {
  15275. return 1;
  15276. }
  15277. if (texture.samples === samples) {
  15278. return samples;
  15279. }
  15280. var gl = this._gl;
  15281. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15282. // Dispose previous render buffers
  15283. if (texture._depthStencilBuffer) {
  15284. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15285. texture._depthStencilBuffer = null;
  15286. }
  15287. if (texture._MSAAFramebuffer) {
  15288. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15289. texture._MSAAFramebuffer = null;
  15290. }
  15291. if (texture._MSAARenderBuffer) {
  15292. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15293. texture._MSAARenderBuffer = null;
  15294. }
  15295. if (samples > 1) {
  15296. var framebuffer = gl.createFramebuffer();
  15297. if (!framebuffer) {
  15298. throw new Error("Unable to create multi sampled framebuffer");
  15299. }
  15300. texture._MSAAFramebuffer = framebuffer;
  15301. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15302. var colorRenderbuffer = gl.createRenderbuffer();
  15303. if (!colorRenderbuffer) {
  15304. throw new Error("Unable to create multi sampled framebuffer");
  15305. }
  15306. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15307. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15308. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15309. texture._MSAARenderBuffer = colorRenderbuffer;
  15310. }
  15311. else {
  15312. this.bindUnboundFramebuffer(texture._framebuffer);
  15313. }
  15314. texture.samples = samples;
  15315. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15316. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15317. this.bindUnboundFramebuffer(null);
  15318. return samples;
  15319. };
  15320. /**
  15321. * Update the sample count for a given multiple render target texture
  15322. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15323. * @param textures defines the textures to update
  15324. * @param samples defines the sample count to set
  15325. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15326. */
  15327. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15328. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15329. return 1;
  15330. }
  15331. if (textures[0].samples === samples) {
  15332. return samples;
  15333. }
  15334. var gl = this._gl;
  15335. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15336. // Dispose previous render buffers
  15337. if (textures[0]._depthStencilBuffer) {
  15338. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15339. textures[0]._depthStencilBuffer = null;
  15340. }
  15341. if (textures[0]._MSAAFramebuffer) {
  15342. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15343. textures[0]._MSAAFramebuffer = null;
  15344. }
  15345. for (var i = 0; i < textures.length; i++) {
  15346. if (textures[i]._MSAARenderBuffer) {
  15347. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15348. textures[i]._MSAARenderBuffer = null;
  15349. }
  15350. }
  15351. if (samples > 1) {
  15352. var framebuffer = gl.createFramebuffer();
  15353. if (!framebuffer) {
  15354. throw new Error("Unable to create multi sampled framebuffer");
  15355. }
  15356. this.bindUnboundFramebuffer(framebuffer);
  15357. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15358. var attachments = [];
  15359. for (var i = 0; i < textures.length; i++) {
  15360. var texture = textures[i];
  15361. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15362. var colorRenderbuffer = gl.createRenderbuffer();
  15363. if (!colorRenderbuffer) {
  15364. throw new Error("Unable to create multi sampled framebuffer");
  15365. }
  15366. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15367. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15368. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15369. texture._MSAAFramebuffer = framebuffer;
  15370. texture._MSAARenderBuffer = colorRenderbuffer;
  15371. texture.samples = samples;
  15372. texture._depthStencilBuffer = depthStencilBuffer;
  15373. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15374. attachments.push(attachment);
  15375. }
  15376. gl.drawBuffers(attachments);
  15377. }
  15378. else {
  15379. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15380. }
  15381. this.bindUnboundFramebuffer(null);
  15382. return samples;
  15383. };
  15384. /** @hidden */
  15385. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15386. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15387. };
  15388. /** @hidden */
  15389. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15390. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15391. };
  15392. /**
  15393. * Creates a new render target cube texture
  15394. * @param size defines the size of the texture
  15395. * @param options defines the options used to create the texture
  15396. * @returns a new render target cube texture stored in an InternalTexture
  15397. */
  15398. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15399. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15400. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15401. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15402. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15403. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15404. }
  15405. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15406. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15407. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15408. }
  15409. var gl = this._gl;
  15410. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15411. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15412. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15413. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15414. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15415. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15416. }
  15417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15421. for (var face = 0; face < 6; face++) {
  15422. 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);
  15423. }
  15424. // Create the framebuffer
  15425. var framebuffer = gl.createFramebuffer();
  15426. this.bindUnboundFramebuffer(framebuffer);
  15427. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15428. // MipMaps
  15429. if (fullOptions.generateMipMaps) {
  15430. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15431. }
  15432. // Unbind
  15433. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15434. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15435. this.bindUnboundFramebuffer(null);
  15436. texture._framebuffer = framebuffer;
  15437. texture.width = size;
  15438. texture.height = size;
  15439. texture.isReady = true;
  15440. texture.isCube = true;
  15441. texture.samples = 1;
  15442. texture.generateMipMaps = fullOptions.generateMipMaps;
  15443. texture.samplingMode = fullOptions.samplingMode;
  15444. texture.type = fullOptions.type;
  15445. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15446. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15447. this._internalTexturesCache.push(texture);
  15448. return texture;
  15449. };
  15450. /**
  15451. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15452. * @param rootUrl defines the url where the file to load is located
  15453. * @param scene defines the current scene
  15454. * @param scale defines scale to apply to the mip map selection
  15455. * @param offset defines offset to apply to the mip map selection
  15456. * @param onLoad defines an optional callback raised when the texture is loaded
  15457. * @param onError defines an optional callback raised if there is an issue to load the texture
  15458. * @param format defines the format of the data
  15459. * @param forcedExtension defines the extension to use to pick the right loader
  15460. * @returns the cube texture as an InternalTexture
  15461. */
  15462. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15463. var _this = this;
  15464. if (onLoad === void 0) { onLoad = null; }
  15465. if (onError === void 0) { onError = null; }
  15466. if (forcedExtension === void 0) { forcedExtension = null; }
  15467. var callback = function (loadData) {
  15468. if (!loadData) {
  15469. if (onLoad) {
  15470. onLoad(null);
  15471. }
  15472. return;
  15473. }
  15474. var texture = loadData.texture;
  15475. if (loadData.info.sphericalPolynomial) {
  15476. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15477. }
  15478. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15479. texture._lodGenerationScale = scale;
  15480. texture._lodGenerationOffset = offset;
  15481. if (_this._caps.textureLOD) {
  15482. // Do not add extra process if texture lod is supported.
  15483. if (onLoad) {
  15484. onLoad(texture);
  15485. }
  15486. return;
  15487. }
  15488. var mipSlices = 3;
  15489. var gl = _this._gl;
  15490. var width = loadData.width;
  15491. if (!width) {
  15492. return;
  15493. }
  15494. var textures = [];
  15495. for (var i = 0; i < mipSlices; i++) {
  15496. //compute LOD from even spacing in smoothness (matching shader calculation)
  15497. var smoothness = i / (mipSlices - 1);
  15498. var roughness = 1 - smoothness;
  15499. var minLODIndex = offset; // roughness = 0
  15500. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15501. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15502. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15503. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15504. glTextureFromLod.isCube = true;
  15505. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15510. if (loadData.isDDS) {
  15511. var info = loadData.info;
  15512. var data = loadData.data;
  15513. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15514. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15515. }
  15516. else {
  15517. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15518. }
  15519. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15520. // Wrap in a base texture for easy binding.
  15521. var lodTexture = new BABYLON.BaseTexture(scene);
  15522. lodTexture.isCube = true;
  15523. lodTexture._texture = glTextureFromLod;
  15524. glTextureFromLod.isReady = true;
  15525. textures.push(lodTexture);
  15526. }
  15527. texture._lodTextureHigh = textures[2];
  15528. texture._lodTextureMid = textures[1];
  15529. texture._lodTextureLow = textures[0];
  15530. if (onLoad) {
  15531. onLoad(texture);
  15532. }
  15533. };
  15534. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15535. };
  15536. /**
  15537. * Creates a cube texture
  15538. * @param rootUrl defines the url where the files to load is located
  15539. * @param scene defines the current scene
  15540. * @param files defines the list of files to load (1 per face)
  15541. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15542. * @param onLoad defines an optional callback raised when the texture is loaded
  15543. * @param onError defines an optional callback raised if there is an issue to load the texture
  15544. * @param format defines the format of the data
  15545. * @param forcedExtension defines the extension to use to pick the right loader
  15546. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15547. * @returns the cube texture as an InternalTexture
  15548. */
  15549. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15550. var _this = this;
  15551. if (onLoad === void 0) { onLoad = null; }
  15552. if (onError === void 0) { onError = null; }
  15553. if (forcedExtension === void 0) { forcedExtension = null; }
  15554. if (createPolynomials === void 0) { createPolynomials = false; }
  15555. var gl = this._gl;
  15556. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15557. texture.isCube = true;
  15558. texture.url = rootUrl;
  15559. texture.generateMipMaps = !noMipmap;
  15560. if (!this._doNotHandleContextLost) {
  15561. texture._extension = forcedExtension;
  15562. texture._files = files;
  15563. }
  15564. var isKTX = false;
  15565. var isDDS = false;
  15566. var lastDot = rootUrl.lastIndexOf('.');
  15567. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15568. if (this._textureFormatInUse) {
  15569. extension = this._textureFormatInUse;
  15570. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15571. isKTX = true;
  15572. }
  15573. else {
  15574. isDDS = (extension === ".dds");
  15575. }
  15576. var onerror = function (request, exception) {
  15577. if (onError && request) {
  15578. onError(request.status + " " + request.statusText, exception);
  15579. }
  15580. };
  15581. if (isKTX) {
  15582. this._loadFile(rootUrl, function (data) {
  15583. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15584. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15585. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15586. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15587. ktx.uploadLevels(_this._gl, !noMipmap);
  15588. _this.setCubeMapTextureParams(gl, loadMipmap);
  15589. texture.width = ktx.pixelWidth;
  15590. texture.height = ktx.pixelHeight;
  15591. texture.isReady = true;
  15592. }, undefined, undefined, true, onerror);
  15593. }
  15594. else if (isDDS) {
  15595. if (files && files.length === 6) {
  15596. this._cascadeLoadFiles(scene, function (imgs) {
  15597. var info;
  15598. var loadMipmap = false;
  15599. var width = 0;
  15600. for (var index = 0; index < imgs.length; index++) {
  15601. var data = imgs[index];
  15602. info = BABYLON.DDSTools.GetDDSInfo(data);
  15603. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15604. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15605. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15606. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15607. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15608. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15609. }
  15610. texture.width = info.width;
  15611. texture.height = info.height;
  15612. texture.type = info.textureType;
  15613. width = info.width;
  15614. }
  15615. _this.setCubeMapTextureParams(gl, loadMipmap);
  15616. texture.isReady = true;
  15617. if (onLoad) {
  15618. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15619. }
  15620. }, files, onError);
  15621. }
  15622. else {
  15623. this._loadFile(rootUrl, function (data) {
  15624. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15625. if (createPolynomials) {
  15626. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15627. }
  15628. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15629. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15630. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15631. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15632. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15633. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15634. }
  15635. _this.setCubeMapTextureParams(gl, loadMipmap);
  15636. texture.width = info.width;
  15637. texture.height = info.height;
  15638. texture.isReady = true;
  15639. texture.type = info.textureType;
  15640. if (onLoad) {
  15641. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15642. }
  15643. }, undefined, undefined, true, onerror);
  15644. }
  15645. }
  15646. else {
  15647. if (!files) {
  15648. throw new Error("Cannot load cubemap because files were not defined");
  15649. }
  15650. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15651. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15652. var height = width;
  15653. _this._prepareWorkingCanvas();
  15654. if (!_this._workingCanvas || !_this._workingContext) {
  15655. return;
  15656. }
  15657. _this._workingCanvas.width = width;
  15658. _this._workingCanvas.height = height;
  15659. var faces = [
  15660. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15661. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15662. ];
  15663. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15664. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15665. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15666. for (var index = 0; index < faces.length; index++) {
  15667. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15668. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15669. }
  15670. if (!noMipmap) {
  15671. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15672. }
  15673. _this.setCubeMapTextureParams(gl, !noMipmap);
  15674. texture.width = width;
  15675. texture.height = height;
  15676. texture.isReady = true;
  15677. if (format) {
  15678. texture.format = format;
  15679. }
  15680. texture.onLoadedObservable.notifyObservers(texture);
  15681. texture.onLoadedObservable.clear();
  15682. if (onLoad) {
  15683. onLoad();
  15684. }
  15685. }, files, onError);
  15686. }
  15687. this._internalTexturesCache.push(texture);
  15688. return texture;
  15689. };
  15690. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15695. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15696. // this.resetTextureCache();
  15697. };
  15698. /**
  15699. * Update a raw cube texture
  15700. * @param texture defines the texture to udpdate
  15701. * @param data defines the data to store
  15702. * @param format defines the data format
  15703. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15704. * @param invertY defines if data must be stored with Y axis inverted
  15705. * @param compression defines the compression used (null by default)
  15706. * @param level defines which level of the texture to update
  15707. */
  15708. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15709. if (compression === void 0) { compression = null; }
  15710. if (level === void 0) { level = 0; }
  15711. texture._bufferViewArray = data;
  15712. texture.format = format;
  15713. texture.type = type;
  15714. texture.invertY = invertY;
  15715. texture._compression = compression;
  15716. var gl = this._gl;
  15717. var textureType = this._getWebGLTextureType(type);
  15718. var internalFormat = this._getInternalFormat(format);
  15719. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15720. var needConversion = false;
  15721. if (internalFormat === gl.RGB) {
  15722. internalFormat = gl.RGBA;
  15723. needConversion = true;
  15724. }
  15725. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15726. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15727. if (texture.width % 4 !== 0) {
  15728. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15729. }
  15730. // Data are known to be in +X +Y +Z -X -Y -Z
  15731. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15732. var faceData = data[faceIndex];
  15733. if (compression) {
  15734. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15735. }
  15736. else {
  15737. if (needConversion) {
  15738. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15739. }
  15740. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15741. }
  15742. }
  15743. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15744. if (isPot && texture.generateMipMaps && level === 0) {
  15745. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15746. }
  15747. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15748. // this.resetTextureCache();
  15749. texture.isReady = true;
  15750. };
  15751. /**
  15752. * Creates a new raw cube texture
  15753. * @param data defines the array of data to use to create each face
  15754. * @param size defines the size of the textures
  15755. * @param format defines the format of the data
  15756. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15757. * @param generateMipMaps defines if the engine should generate the mip levels
  15758. * @param invertY defines if data must be stored with Y axis inverted
  15759. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15760. * @param compression defines the compression used (null by default)
  15761. * @returns the cube texture as an InternalTexture
  15762. */
  15763. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15764. if (compression === void 0) { compression = null; }
  15765. var gl = this._gl;
  15766. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15767. texture.isCube = true;
  15768. texture.generateMipMaps = generateMipMaps;
  15769. texture.format = format;
  15770. texture.type = type;
  15771. if (!this._doNotHandleContextLost) {
  15772. texture._bufferViewArray = data;
  15773. }
  15774. var textureType = this._getWebGLTextureType(type);
  15775. var internalFormat = this._getInternalFormat(format);
  15776. if (internalFormat === gl.RGB) {
  15777. internalFormat = gl.RGBA;
  15778. }
  15779. var width = size;
  15780. var height = width;
  15781. texture.width = width;
  15782. texture.height = height;
  15783. // Double check on POT to generate Mips.
  15784. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15785. if (!isPot) {
  15786. generateMipMaps = false;
  15787. }
  15788. // Upload data if needed. The texture won't be ready until then.
  15789. if (data) {
  15790. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15791. }
  15792. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15793. // Filters
  15794. if (data && generateMipMaps) {
  15795. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15796. }
  15797. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15800. }
  15801. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15804. }
  15805. else {
  15806. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15809. }
  15810. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15811. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15812. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15813. return texture;
  15814. };
  15815. /**
  15816. * Creates a new raw cube texture from a specified url
  15817. * @param url defines the url where the data is located
  15818. * @param scene defines the current scene
  15819. * @param size defines the size of the textures
  15820. * @param format defines the format of the data
  15821. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15822. * @param noMipmap defines if the engine should avoid generating the mip levels
  15823. * @param callback defines a callback used to extract texture data from loaded data
  15824. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15825. * @param onLoad defines a callback called when texture is loaded
  15826. * @param onError defines a callback called if there is an error
  15827. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15828. * @param invertY defines if data must be stored with Y axis inverted
  15829. * @returns the cube texture as an InternalTexture
  15830. */
  15831. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15832. var _this = this;
  15833. if (onLoad === void 0) { onLoad = null; }
  15834. if (onError === void 0) { onError = null; }
  15835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15836. if (invertY === void 0) { invertY = false; }
  15837. var gl = this._gl;
  15838. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15839. scene._addPendingData(texture);
  15840. texture.url = url;
  15841. this._internalTexturesCache.push(texture);
  15842. var onerror = function (request, exception) {
  15843. scene._removePendingData(texture);
  15844. if (onError && request) {
  15845. onError(request.status + " " + request.statusText, exception);
  15846. }
  15847. };
  15848. var internalCallback = function (data) {
  15849. var width = texture.width;
  15850. var faceDataArrays = callback(data);
  15851. if (!faceDataArrays) {
  15852. return;
  15853. }
  15854. if (mipmapGenerator) {
  15855. var textureType = _this._getWebGLTextureType(type);
  15856. var internalFormat = _this._getInternalFormat(format);
  15857. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15858. var needConversion = false;
  15859. if (internalFormat === gl.RGB) {
  15860. internalFormat = gl.RGBA;
  15861. needConversion = true;
  15862. }
  15863. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15864. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15865. var mipData = mipmapGenerator(faceDataArrays);
  15866. for (var level = 0; level < mipData.length; level++) {
  15867. var mipSize = width >> level;
  15868. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15869. var mipFaceData = mipData[level][faceIndex];
  15870. if (needConversion) {
  15871. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15872. }
  15873. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15874. }
  15875. }
  15876. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15877. }
  15878. else {
  15879. texture.generateMipMaps = !noMipmap;
  15880. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15881. }
  15882. texture.isReady = true;
  15883. // this.resetTextureCache();
  15884. scene._removePendingData(texture);
  15885. if (onLoad) {
  15886. onLoad();
  15887. }
  15888. };
  15889. this._loadFile(url, function (data) {
  15890. internalCallback(data);
  15891. }, undefined, scene.database, true, onerror);
  15892. return texture;
  15893. };
  15894. ;
  15895. /**
  15896. * Update a raw 3D texture
  15897. * @param texture defines the texture to update
  15898. * @param data defines the data to store
  15899. * @param format defines the data format
  15900. * @param invertY defines if data must be stored with Y axis inverted
  15901. * @param compression defines the used compression (can be null)
  15902. */
  15903. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15904. if (compression === void 0) { compression = null; }
  15905. var internalFormat = this._getInternalFormat(format);
  15906. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15907. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15908. if (!this._doNotHandleContextLost) {
  15909. texture._bufferView = data;
  15910. texture.format = format;
  15911. texture.invertY = invertY;
  15912. texture._compression = compression;
  15913. }
  15914. if (texture.width % 4 !== 0) {
  15915. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15916. }
  15917. if (compression && data) {
  15918. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15919. }
  15920. else {
  15921. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15922. }
  15923. if (texture.generateMipMaps) {
  15924. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15925. }
  15926. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15927. // this.resetTextureCache();
  15928. texture.isReady = true;
  15929. };
  15930. /**
  15931. * Creates a new raw 3D texture
  15932. * @param data defines the data used to create the texture
  15933. * @param width defines the width of the texture
  15934. * @param height defines the height of the texture
  15935. * @param depth defines the depth of the texture
  15936. * @param format defines the format of the texture
  15937. * @param generateMipMaps defines if the engine must generate mip levels
  15938. * @param invertY defines if data must be stored with Y axis inverted
  15939. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15940. * @param compression defines the compressed used (can be null)
  15941. * @returns a new raw 3D texture (stored in an InternalTexture)
  15942. */
  15943. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15944. if (compression === void 0) { compression = null; }
  15945. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15946. texture.baseWidth = width;
  15947. texture.baseHeight = height;
  15948. texture.baseDepth = depth;
  15949. texture.width = width;
  15950. texture.height = height;
  15951. texture.depth = depth;
  15952. texture.format = format;
  15953. texture.generateMipMaps = generateMipMaps;
  15954. texture.samplingMode = samplingMode;
  15955. texture.is3D = true;
  15956. if (!this._doNotHandleContextLost) {
  15957. texture._bufferView = data;
  15958. }
  15959. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15960. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15961. // Filters
  15962. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15963. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15964. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15965. if (generateMipMaps) {
  15966. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15967. }
  15968. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15969. this._internalTexturesCache.push(texture);
  15970. return texture;
  15971. };
  15972. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15973. var gl = this._gl;
  15974. if (!gl) {
  15975. return;
  15976. }
  15977. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15980. if (!noMipmap && !isCompressed) {
  15981. gl.generateMipmap(gl.TEXTURE_2D);
  15982. }
  15983. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15984. // this.resetTextureCache();
  15985. if (scene) {
  15986. scene._removePendingData(texture);
  15987. }
  15988. texture.onLoadedObservable.notifyObservers(texture);
  15989. texture.onLoadedObservable.clear();
  15990. };
  15991. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15992. var _this = this;
  15993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15994. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15995. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15996. var gl = this._gl;
  15997. if (!gl) {
  15998. return;
  15999. }
  16000. if (!texture._webGLTexture) {
  16001. // this.resetTextureCache();
  16002. if (scene) {
  16003. scene._removePendingData(texture);
  16004. }
  16005. return;
  16006. }
  16007. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16008. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16009. texture.baseWidth = width;
  16010. texture.baseHeight = height;
  16011. texture.width = potWidth;
  16012. texture.height = potHeight;
  16013. texture.isReady = true;
  16014. if (processFunction(potWidth, potHeight, function () {
  16015. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16016. })) {
  16017. // Returning as texture needs extra async steps
  16018. return;
  16019. }
  16020. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16021. };
  16022. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16023. // Create new RGBA data container.
  16024. var rgbaData;
  16025. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16026. rgbaData = new Float32Array(width * height * 4);
  16027. }
  16028. else {
  16029. rgbaData = new Uint32Array(width * height * 4);
  16030. }
  16031. // Convert each pixel.
  16032. for (var x = 0; x < width; x++) {
  16033. for (var y = 0; y < height; y++) {
  16034. var index = (y * width + x) * 3;
  16035. var newIndex = (y * width + x) * 4;
  16036. // Map Old Value to new value.
  16037. rgbaData[newIndex + 0] = rgbData[index + 0];
  16038. rgbaData[newIndex + 1] = rgbData[index + 1];
  16039. rgbaData[newIndex + 2] = rgbData[index + 2];
  16040. // Add fully opaque alpha channel.
  16041. rgbaData[newIndex + 3] = 1;
  16042. }
  16043. }
  16044. return rgbaData;
  16045. };
  16046. /** @hidden */
  16047. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16048. var gl = this._gl;
  16049. if (texture._framebuffer) {
  16050. gl.deleteFramebuffer(texture._framebuffer);
  16051. texture._framebuffer = null;
  16052. }
  16053. if (texture._depthStencilBuffer) {
  16054. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16055. texture._depthStencilBuffer = null;
  16056. }
  16057. if (texture._MSAAFramebuffer) {
  16058. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16059. texture._MSAAFramebuffer = null;
  16060. }
  16061. if (texture._MSAARenderBuffer) {
  16062. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16063. texture._MSAARenderBuffer = null;
  16064. }
  16065. };
  16066. /** @hidden */
  16067. Engine.prototype._releaseTexture = function (texture) {
  16068. var gl = this._gl;
  16069. this._releaseFramebufferObjects(texture);
  16070. gl.deleteTexture(texture._webGLTexture);
  16071. // Unbind channels
  16072. this.unbindAllTextures();
  16073. var index = this._internalTexturesCache.indexOf(texture);
  16074. if (index !== -1) {
  16075. this._internalTexturesCache.splice(index, 1);
  16076. }
  16077. // Integrated fixed lod samplers.
  16078. if (texture._lodTextureHigh) {
  16079. texture._lodTextureHigh.dispose();
  16080. }
  16081. if (texture._lodTextureMid) {
  16082. texture._lodTextureMid.dispose();
  16083. }
  16084. if (texture._lodTextureLow) {
  16085. texture._lodTextureLow.dispose();
  16086. }
  16087. // Set output texture of post process to null if the texture has been released/disposed
  16088. this.scenes.forEach(function (scene) {
  16089. scene.postProcesses.forEach(function (postProcess) {
  16090. if (postProcess._outputTexture == texture) {
  16091. postProcess._outputTexture = null;
  16092. }
  16093. });
  16094. scene.cameras.forEach(function (camera) {
  16095. camera._postProcesses.forEach(function (postProcess) {
  16096. if (postProcess) {
  16097. if (postProcess._outputTexture == texture) {
  16098. postProcess._outputTexture = null;
  16099. }
  16100. }
  16101. });
  16102. });
  16103. });
  16104. };
  16105. Engine.prototype.setProgram = function (program) {
  16106. if (this._currentProgram !== program) {
  16107. this._gl.useProgram(program);
  16108. this._currentProgram = program;
  16109. }
  16110. };
  16111. /**
  16112. * Binds an effect to the webGL context
  16113. * @param effect defines the effect to bind
  16114. */
  16115. Engine.prototype.bindSamplers = function (effect) {
  16116. this.setProgram(effect.getProgram());
  16117. var samplers = effect.getSamplers();
  16118. for (var index = 0; index < samplers.length; index++) {
  16119. var uniform = effect.getUniform(samplers[index]);
  16120. if (uniform) {
  16121. this._boundUniforms[index] = uniform;
  16122. }
  16123. }
  16124. this._currentEffect = null;
  16125. };
  16126. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16127. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16128. return;
  16129. }
  16130. // Remove
  16131. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16132. // Bind last to it
  16133. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16134. // Bind to dummy
  16135. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16136. };
  16137. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16138. if (!internalTexture) {
  16139. return -1;
  16140. }
  16141. internalTexture._initialSlot = channel;
  16142. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16143. if (channel !== internalTexture._designatedSlot) {
  16144. this._textureCollisions.addCount(1, false);
  16145. }
  16146. }
  16147. else {
  16148. if (channel !== internalTexture._designatedSlot) {
  16149. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16150. return internalTexture._designatedSlot;
  16151. }
  16152. else {
  16153. // No slot for this texture, let's pick a new one (if we find a free slot)
  16154. if (this._nextFreeTextureSlots.length) {
  16155. return this._nextFreeTextureSlots[0];
  16156. }
  16157. // We need to recycle the oldest bound texture, sorry.
  16158. this._textureCollisions.addCount(1, false);
  16159. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16160. }
  16161. }
  16162. }
  16163. return channel;
  16164. };
  16165. Engine.prototype._linkTrackers = function (previous, next) {
  16166. previous.next = next;
  16167. next.previous = previous;
  16168. };
  16169. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16170. var currentSlot = internalTexture._designatedSlot;
  16171. if (currentSlot === -1) {
  16172. return -1;
  16173. }
  16174. internalTexture._designatedSlot = -1;
  16175. if (this.disableTextureBindingOptimization) {
  16176. return -1;
  16177. }
  16178. // Remove from bound list
  16179. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16180. // Free the slot
  16181. this._boundTexturesCache[currentSlot] = null;
  16182. this._nextFreeTextureSlots.push(currentSlot);
  16183. return currentSlot;
  16184. };
  16185. Engine.prototype._activateCurrentTexture = function () {
  16186. if (this._currentTextureChannel !== this._activeChannel) {
  16187. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16188. this._currentTextureChannel = this._activeChannel;
  16189. }
  16190. };
  16191. /** @hidden */
  16192. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16193. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16194. if (force === void 0) { force = false; }
  16195. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16196. this._activeChannel = texture._designatedSlot;
  16197. }
  16198. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16199. var isTextureForRendering = texture && texture._initialSlot > -1;
  16200. if (currentTextureBound !== texture || force) {
  16201. if (currentTextureBound) {
  16202. this._removeDesignatedSlot(currentTextureBound);
  16203. }
  16204. this._activateCurrentTexture();
  16205. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16206. this._boundTexturesCache[this._activeChannel] = texture;
  16207. if (texture) {
  16208. if (!this.disableTextureBindingOptimization) {
  16209. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16210. if (slotIndex > -1) {
  16211. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16212. }
  16213. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16214. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16215. }
  16216. texture._designatedSlot = this._activeChannel;
  16217. }
  16218. }
  16219. else if (forTextureDataUpdate) {
  16220. this._activateCurrentTexture();
  16221. }
  16222. if (isTextureForRendering && !forTextureDataUpdate) {
  16223. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16224. }
  16225. };
  16226. /** @hidden */
  16227. Engine.prototype._bindTexture = function (channel, texture) {
  16228. if (channel < 0) {
  16229. return;
  16230. }
  16231. if (texture) {
  16232. channel = this._getCorrectTextureChannel(channel, texture);
  16233. }
  16234. this._activeChannel = channel;
  16235. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16236. };
  16237. /**
  16238. * Sets a texture to the webGL context from a postprocess
  16239. * @param channel defines the channel to use
  16240. * @param postProcess defines the source postprocess
  16241. */
  16242. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16243. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16244. };
  16245. /**
  16246. * Binds the output of the passed in post process to the texture channel specified
  16247. * @param channel The channel the texture should be bound to
  16248. * @param postProcess The post process which's output should be bound
  16249. */
  16250. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16251. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16252. };
  16253. /**
  16254. * Unbind all textures from the webGL context
  16255. */
  16256. Engine.prototype.unbindAllTextures = function () {
  16257. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16258. this._activeChannel = channel;
  16259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16260. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16261. if (this.webGLVersion > 1) {
  16262. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16263. }
  16264. }
  16265. };
  16266. /**
  16267. * Sets a texture to the according uniform.
  16268. * @param channel The texture channel
  16269. * @param uniform The uniform to set
  16270. * @param texture The texture to apply
  16271. */
  16272. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16273. if (channel < 0) {
  16274. return;
  16275. }
  16276. if (uniform) {
  16277. this._boundUniforms[channel] = uniform;
  16278. }
  16279. this._setTexture(channel, texture);
  16280. };
  16281. /**
  16282. * Sets a depth stencil texture from a render target to the according uniform.
  16283. * @param channel The texture channel
  16284. * @param uniform The uniform to set
  16285. * @param texture The render target texture containing the depth stencil texture to apply
  16286. */
  16287. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16288. if (channel < 0) {
  16289. return;
  16290. }
  16291. if (uniform) {
  16292. this._boundUniforms[channel] = uniform;
  16293. }
  16294. if (!texture || !texture.depthStencilTexture) {
  16295. this._setTexture(channel, null);
  16296. }
  16297. else {
  16298. this._setTexture(channel, texture, false, true);
  16299. }
  16300. };
  16301. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16302. var uniform = this._boundUniforms[sourceSlot];
  16303. if (uniform._currentState === destination) {
  16304. return;
  16305. }
  16306. this._gl.uniform1i(uniform, destination);
  16307. uniform._currentState = destination;
  16308. };
  16309. Engine.prototype._getTextureWrapMode = function (mode) {
  16310. switch (mode) {
  16311. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16312. return this._gl.REPEAT;
  16313. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16314. return this._gl.CLAMP_TO_EDGE;
  16315. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16316. return this._gl.MIRRORED_REPEAT;
  16317. }
  16318. return this._gl.REPEAT;
  16319. };
  16320. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16321. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16322. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16323. // Not ready?
  16324. if (!texture) {
  16325. if (this._boundTexturesCache[channel] != null) {
  16326. this._activeChannel = channel;
  16327. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16328. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16329. if (this.webGLVersion > 1) {
  16330. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16331. }
  16332. }
  16333. return false;
  16334. }
  16335. // Video
  16336. if (texture.video) {
  16337. this._activeChannel = channel;
  16338. texture.update();
  16339. }
  16340. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16341. texture.delayLoad();
  16342. return false;
  16343. }
  16344. var internalTexture;
  16345. if (depthStencilTexture) {
  16346. internalTexture = texture.depthStencilTexture;
  16347. }
  16348. else if (texture.isReady()) {
  16349. internalTexture = texture.getInternalTexture();
  16350. }
  16351. else if (texture.isCube) {
  16352. internalTexture = this.emptyCubeTexture;
  16353. }
  16354. else if (texture.is3D) {
  16355. internalTexture = this.emptyTexture3D;
  16356. }
  16357. else {
  16358. internalTexture = this.emptyTexture;
  16359. }
  16360. if (!isPartOfTextureArray) {
  16361. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16362. }
  16363. var needToBind = true;
  16364. if (this._boundTexturesCache[channel] === internalTexture) {
  16365. this._moveBoundTextureOnTop(internalTexture);
  16366. if (!isPartOfTextureArray) {
  16367. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16368. }
  16369. needToBind = false;
  16370. }
  16371. this._activeChannel = channel;
  16372. if (internalTexture && internalTexture.is3D) {
  16373. if (needToBind) {
  16374. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16375. }
  16376. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16377. internalTexture._cachedWrapU = texture.wrapU;
  16378. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16379. }
  16380. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16381. internalTexture._cachedWrapV = texture.wrapV;
  16382. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16383. }
  16384. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16385. internalTexture._cachedWrapR = texture.wrapR;
  16386. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16387. }
  16388. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16389. }
  16390. else if (internalTexture && internalTexture.isCube) {
  16391. if (needToBind) {
  16392. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16393. }
  16394. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16395. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16396. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16397. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16398. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16399. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16400. }
  16401. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16402. }
  16403. else {
  16404. if (needToBind) {
  16405. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16406. }
  16407. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16408. internalTexture._cachedWrapU = texture.wrapU;
  16409. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16410. }
  16411. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16412. internalTexture._cachedWrapV = texture.wrapV;
  16413. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16414. }
  16415. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16416. }
  16417. return true;
  16418. };
  16419. /**
  16420. * Sets an array of texture to the webGL context
  16421. * @param channel defines the channel where the texture array must be set
  16422. * @param uniform defines the associated uniform location
  16423. * @param textures defines the array of textures to bind
  16424. */
  16425. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16426. if (channel < 0 || !uniform) {
  16427. return;
  16428. }
  16429. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16430. this._textureUnits = new Int32Array(textures.length);
  16431. }
  16432. for (var i = 0; i < textures.length; i++) {
  16433. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16434. }
  16435. this._gl.uniform1iv(uniform, this._textureUnits);
  16436. for (var index = 0; index < textures.length; index++) {
  16437. this._setTexture(this._textureUnits[index], textures[index], true);
  16438. }
  16439. };
  16440. /** @hidden */
  16441. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16442. var internalTexture = texture.getInternalTexture();
  16443. if (!internalTexture) {
  16444. return;
  16445. }
  16446. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16447. var value = texture.anisotropicFilteringLevel;
  16448. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16449. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16450. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16451. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16452. }
  16453. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16454. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16455. internalTexture._cachedAnisotropicFilteringLevel = value;
  16456. }
  16457. };
  16458. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16459. this._bindTextureDirectly(target, texture, true, true);
  16460. this._gl.texParameterf(target, parameter, value);
  16461. };
  16462. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16463. if (texture) {
  16464. this._bindTextureDirectly(target, texture, true, true);
  16465. }
  16466. this._gl.texParameteri(target, parameter, value);
  16467. };
  16468. /**
  16469. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16470. * @param x defines the x coordinate of the rectangle where pixels must be read
  16471. * @param y defines the y coordinate of the rectangle where pixels must be read
  16472. * @param width defines the width of the rectangle where pixels must be read
  16473. * @param height defines the height of the rectangle where pixels must be read
  16474. * @returns a Uint8Array containing RGBA colors
  16475. */
  16476. Engine.prototype.readPixels = function (x, y, width, height) {
  16477. var data = new Uint8Array(height * width * 4);
  16478. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16479. return data;
  16480. };
  16481. /**
  16482. * Add an externaly attached data from its key.
  16483. * This method call will fail and return false, if such key already exists.
  16484. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16485. * @param key the unique key that identifies the data
  16486. * @param data the data object to associate to the key for this Engine instance
  16487. * @return true if no such key were already present and the data was added successfully, false otherwise
  16488. */
  16489. Engine.prototype.addExternalData = function (key, data) {
  16490. if (!this._externalData) {
  16491. this._externalData = new BABYLON.StringDictionary();
  16492. }
  16493. return this._externalData.add(key, data);
  16494. };
  16495. /**
  16496. * Get an externaly attached data from its key
  16497. * @param key the unique key that identifies the data
  16498. * @return the associated data, if present (can be null), or undefined if not present
  16499. */
  16500. Engine.prototype.getExternalData = function (key) {
  16501. if (!this._externalData) {
  16502. this._externalData = new BABYLON.StringDictionary();
  16503. }
  16504. return this._externalData.get(key);
  16505. };
  16506. /**
  16507. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16508. * @param key the unique key that identifies the data
  16509. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16510. * @return the associated data, can be null if the factory returned null.
  16511. */
  16512. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16513. if (!this._externalData) {
  16514. this._externalData = new BABYLON.StringDictionary();
  16515. }
  16516. return this._externalData.getOrAddWithFactory(key, factory);
  16517. };
  16518. /**
  16519. * Remove an externaly attached data from the Engine instance
  16520. * @param key the unique key that identifies the data
  16521. * @return true if the data was successfully removed, false if it doesn't exist
  16522. */
  16523. Engine.prototype.removeExternalData = function (key) {
  16524. if (!this._externalData) {
  16525. this._externalData = new BABYLON.StringDictionary();
  16526. }
  16527. return this._externalData.remove(key);
  16528. };
  16529. /**
  16530. * Unbind all vertex attributes from the webGL context
  16531. */
  16532. Engine.prototype.unbindAllAttributes = function () {
  16533. if (this._mustWipeVertexAttributes) {
  16534. this._mustWipeVertexAttributes = false;
  16535. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16536. this._gl.disableVertexAttribArray(i);
  16537. this._vertexAttribArraysEnabled[i] = false;
  16538. this._currentBufferPointers[i].active = false;
  16539. }
  16540. return;
  16541. }
  16542. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16543. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16544. continue;
  16545. }
  16546. this._gl.disableVertexAttribArray(i);
  16547. this._vertexAttribArraysEnabled[i] = false;
  16548. this._currentBufferPointers[i].active = false;
  16549. }
  16550. };
  16551. /**
  16552. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16553. */
  16554. Engine.prototype.releaseEffects = function () {
  16555. for (var name in this._compiledEffects) {
  16556. this._deleteProgram(this._compiledEffects[name]._program);
  16557. }
  16558. this._compiledEffects = {};
  16559. };
  16560. /**
  16561. * Dispose and release all associated resources
  16562. */
  16563. Engine.prototype.dispose = function () {
  16564. this.hideLoadingUI();
  16565. this.stopRenderLoop();
  16566. // Release postProcesses
  16567. while (this.postProcesses.length) {
  16568. this.postProcesses[0].dispose();
  16569. }
  16570. // Empty texture
  16571. if (this._emptyTexture) {
  16572. this._releaseTexture(this._emptyTexture);
  16573. this._emptyTexture = null;
  16574. }
  16575. if (this._emptyCubeTexture) {
  16576. this._releaseTexture(this._emptyCubeTexture);
  16577. this._emptyCubeTexture = null;
  16578. }
  16579. // Rescale PP
  16580. if (this._rescalePostProcess) {
  16581. this._rescalePostProcess.dispose();
  16582. }
  16583. // Release scenes
  16584. while (this.scenes.length) {
  16585. this.scenes[0].dispose();
  16586. }
  16587. // Release audio engine
  16588. if (Engine.audioEngine) {
  16589. Engine.audioEngine.dispose();
  16590. }
  16591. // Release effects
  16592. this.releaseEffects();
  16593. // Unbind
  16594. this.unbindAllAttributes();
  16595. this._boundUniforms = [];
  16596. if (this._dummyFramebuffer) {
  16597. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16598. }
  16599. //WebVR
  16600. this.disableVR();
  16601. // Events
  16602. if (BABYLON.Tools.IsWindowObjectExist()) {
  16603. window.removeEventListener("blur", this._onBlur);
  16604. window.removeEventListener("focus", this._onFocus);
  16605. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16606. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16607. if (this._renderingCanvas) {
  16608. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16609. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16610. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16611. if (!this._doNotHandleContextLost) {
  16612. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16613. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16614. }
  16615. }
  16616. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16617. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16618. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16619. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16620. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16621. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16622. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16623. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16624. if (this._onVrDisplayConnect) {
  16625. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16626. if (this._onVrDisplayDisconnect) {
  16627. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16628. }
  16629. if (this._onVrDisplayPresentChange) {
  16630. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16631. }
  16632. this._onVrDisplayConnect = null;
  16633. this._onVrDisplayDisconnect = null;
  16634. }
  16635. }
  16636. // Remove from Instances
  16637. var index = Engine.Instances.indexOf(this);
  16638. if (index >= 0) {
  16639. Engine.Instances.splice(index, 1);
  16640. }
  16641. this._workingCanvas = null;
  16642. this._workingContext = null;
  16643. this._currentBufferPointers = [];
  16644. this._renderingCanvas = null;
  16645. this._currentProgram = null;
  16646. this._bindedRenderFunction = null;
  16647. this.onResizeObservable.clear();
  16648. this.onCanvasBlurObservable.clear();
  16649. this.onCanvasFocusObservable.clear();
  16650. this.onCanvasPointerOutObservable.clear();
  16651. this.onBeginFrameObservable.clear();
  16652. this.onEndFrameObservable.clear();
  16653. BABYLON.Effect.ResetCache();
  16654. // Abort active requests
  16655. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16656. var request = _a[_i];
  16657. request.abort();
  16658. }
  16659. };
  16660. // Loading screen
  16661. /**
  16662. * Display the loading screen
  16663. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16664. */
  16665. Engine.prototype.displayLoadingUI = function () {
  16666. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16667. return;
  16668. }
  16669. var loadingScreen = this.loadingScreen;
  16670. if (loadingScreen) {
  16671. loadingScreen.displayLoadingUI();
  16672. }
  16673. };
  16674. /**
  16675. * Hide the loading screen
  16676. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16677. */
  16678. Engine.prototype.hideLoadingUI = function () {
  16679. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16680. return;
  16681. }
  16682. var loadingScreen = this.loadingScreen;
  16683. if (loadingScreen) {
  16684. loadingScreen.hideLoadingUI();
  16685. }
  16686. };
  16687. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16688. /**
  16689. * Gets the current loading screen object
  16690. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16691. */
  16692. get: function () {
  16693. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16694. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16695. return this._loadingScreen;
  16696. },
  16697. /**
  16698. * Sets the current loading screen object
  16699. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16700. */
  16701. set: function (loadingScreen) {
  16702. this._loadingScreen = loadingScreen;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16708. /**
  16709. * Sets the current loading screen text
  16710. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16711. */
  16712. set: function (text) {
  16713. this.loadingScreen.loadingUIText = text;
  16714. },
  16715. enumerable: true,
  16716. configurable: true
  16717. });
  16718. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16719. /**
  16720. * Sets the current loading screen background color
  16721. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16722. */
  16723. set: function (color) {
  16724. this.loadingScreen.loadingUIBackgroundColor = color;
  16725. },
  16726. enumerable: true,
  16727. configurable: true
  16728. });
  16729. /**
  16730. * Attach a new callback raised when context lost event is fired
  16731. * @param callback defines the callback to call
  16732. */
  16733. Engine.prototype.attachContextLostEvent = function (callback) {
  16734. if (this._renderingCanvas) {
  16735. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16736. }
  16737. };
  16738. /**
  16739. * Attach a new callback raised when context restored event is fired
  16740. * @param callback defines the callback to call
  16741. */
  16742. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16743. if (this._renderingCanvas) {
  16744. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16745. }
  16746. };
  16747. /**
  16748. * Gets the source code of the vertex shader associated with a specific webGL program
  16749. * @param program defines the program to use
  16750. * @returns a string containing the source code of the vertex shader associated with the program
  16751. */
  16752. Engine.prototype.getVertexShaderSource = function (program) {
  16753. var shaders = this._gl.getAttachedShaders(program);
  16754. if (!shaders) {
  16755. return null;
  16756. }
  16757. return this._gl.getShaderSource(shaders[0]);
  16758. };
  16759. /**
  16760. * Gets the source code of the fragment shader associated with a specific webGL program
  16761. * @param program defines the program to use
  16762. * @returns a string containing the source code of the fragment shader associated with the program
  16763. */
  16764. Engine.prototype.getFragmentShaderSource = function (program) {
  16765. var shaders = this._gl.getAttachedShaders(program);
  16766. if (!shaders) {
  16767. return null;
  16768. }
  16769. return this._gl.getShaderSource(shaders[1]);
  16770. };
  16771. /**
  16772. * Get the current error code of the webGL context
  16773. * @returns the error code
  16774. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16775. */
  16776. Engine.prototype.getError = function () {
  16777. return this._gl.getError();
  16778. };
  16779. // FPS
  16780. /**
  16781. * Gets the current framerate
  16782. * @returns a number representing the framerate
  16783. */
  16784. Engine.prototype.getFps = function () {
  16785. return this._fps;
  16786. };
  16787. /**
  16788. * Gets the time spent between current and previous frame
  16789. * @returns a number representing the delta time in ms
  16790. */
  16791. Engine.prototype.getDeltaTime = function () {
  16792. return this._deltaTime;
  16793. };
  16794. Engine.prototype._measureFps = function () {
  16795. this._performanceMonitor.sampleFrame();
  16796. this._fps = this._performanceMonitor.averageFPS;
  16797. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16798. };
  16799. /** @hidden */
  16800. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16801. if (faceIndex === void 0) { faceIndex = -1; }
  16802. var gl = this._gl;
  16803. if (!this._dummyFramebuffer) {
  16804. var dummy = gl.createFramebuffer();
  16805. if (!dummy) {
  16806. throw new Error("Unable to create dummy framebuffer");
  16807. }
  16808. this._dummyFramebuffer = dummy;
  16809. }
  16810. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16811. if (faceIndex > -1) {
  16812. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16813. }
  16814. else {
  16815. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16816. }
  16817. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16818. var buffer;
  16819. switch (readType) {
  16820. case gl.UNSIGNED_BYTE:
  16821. buffer = new Uint8Array(4 * width * height);
  16822. readType = gl.UNSIGNED_BYTE;
  16823. break;
  16824. default:
  16825. buffer = new Float32Array(4 * width * height);
  16826. readType = gl.FLOAT;
  16827. break;
  16828. }
  16829. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16830. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16831. return buffer;
  16832. };
  16833. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16834. if (this._webGLVersion > 1) {
  16835. return this._caps.colorBufferFloat;
  16836. }
  16837. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16838. };
  16839. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16840. if (this._webGLVersion > 1) {
  16841. return this._caps.colorBufferFloat;
  16842. }
  16843. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16844. };
  16845. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16846. Engine.prototype._canRenderToFramebuffer = function (type) {
  16847. var gl = this._gl;
  16848. //clear existing errors
  16849. while (gl.getError() !== gl.NO_ERROR) { }
  16850. var successful = true;
  16851. var texture = gl.createTexture();
  16852. gl.bindTexture(gl.TEXTURE_2D, texture);
  16853. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16856. var fb = gl.createFramebuffer();
  16857. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16858. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16859. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16860. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16861. successful = successful && (gl.getError() === gl.NO_ERROR);
  16862. //try render by clearing frame buffer's color buffer
  16863. if (successful) {
  16864. gl.clear(gl.COLOR_BUFFER_BIT);
  16865. successful = successful && (gl.getError() === gl.NO_ERROR);
  16866. }
  16867. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16868. if (successful) {
  16869. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16870. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16871. var readFormat = gl.RGBA;
  16872. var readType = gl.UNSIGNED_BYTE;
  16873. var buffer = new Uint8Array(4);
  16874. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16875. successful = successful && (gl.getError() === gl.NO_ERROR);
  16876. }
  16877. //clean up
  16878. gl.deleteTexture(texture);
  16879. gl.deleteFramebuffer(fb);
  16880. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16881. //clear accumulated errors
  16882. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16883. return successful;
  16884. };
  16885. /** @hidden */
  16886. Engine.prototype._getWebGLTextureType = function (type) {
  16887. if (type === Engine.TEXTURETYPE_FLOAT) {
  16888. return this._gl.FLOAT;
  16889. }
  16890. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16891. // Add Half Float Constant.
  16892. return this._gl.HALF_FLOAT_OES;
  16893. }
  16894. return this._gl.UNSIGNED_BYTE;
  16895. };
  16896. ;
  16897. Engine.prototype._getInternalFormat = function (format) {
  16898. var internalFormat = this._gl.RGBA;
  16899. switch (format) {
  16900. case Engine.TEXTUREFORMAT_ALPHA:
  16901. internalFormat = this._gl.ALPHA;
  16902. break;
  16903. case Engine.TEXTUREFORMAT_LUMINANCE:
  16904. internalFormat = this._gl.LUMINANCE;
  16905. break;
  16906. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16907. internalFormat = this._gl.LUMINANCE_ALPHA;
  16908. break;
  16909. case Engine.TEXTUREFORMAT_RGB:
  16910. case Engine.TEXTUREFORMAT_RGB32F:
  16911. internalFormat = this._gl.RGB;
  16912. break;
  16913. case Engine.TEXTUREFORMAT_RGBA:
  16914. case Engine.TEXTUREFORMAT_RGBA32F:
  16915. internalFormat = this._gl.RGBA;
  16916. break;
  16917. case Engine.TEXTUREFORMAT_R32F:
  16918. internalFormat = this._gl.RED;
  16919. break;
  16920. case Engine.TEXTUREFORMAT_RG32F:
  16921. internalFormat = this._gl.RG;
  16922. break;
  16923. }
  16924. return internalFormat;
  16925. };
  16926. /** @hidden */
  16927. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16928. if (this._webGLVersion === 1) {
  16929. if (format) {
  16930. switch (format) {
  16931. case Engine.TEXTUREFORMAT_LUMINANCE:
  16932. return this._gl.LUMINANCE;
  16933. }
  16934. }
  16935. return this._gl.RGBA;
  16936. }
  16937. if (type === Engine.TEXTURETYPE_FLOAT) {
  16938. if (format) {
  16939. switch (format) {
  16940. case Engine.TEXTUREFORMAT_R32F:
  16941. return this._gl.R32F;
  16942. case Engine.TEXTUREFORMAT_RG32F:
  16943. return this._gl.RG32F;
  16944. case Engine.TEXTUREFORMAT_RGB32F:
  16945. return this._gl.RGB32F;
  16946. }
  16947. }
  16948. return this._gl.RGBA32F;
  16949. }
  16950. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16951. return this._gl.RGBA16F;
  16952. }
  16953. if (format) {
  16954. switch (format) {
  16955. case Engine.TEXTUREFORMAT_LUMINANCE:
  16956. return this._gl.LUMINANCE;
  16957. case Engine.TEXTUREFORMAT_RGB:
  16958. return this._gl.RGB;
  16959. }
  16960. }
  16961. return this._gl.RGBA;
  16962. };
  16963. ;
  16964. /** @hidden */
  16965. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16966. if (type === Engine.TEXTURETYPE_FLOAT) {
  16967. return this._gl.RGBA32F;
  16968. }
  16969. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16970. return this._gl.RGBA16F;
  16971. }
  16972. return this._gl.RGBA8;
  16973. };
  16974. ;
  16975. /**
  16976. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16977. * @return the new query
  16978. */
  16979. Engine.prototype.createQuery = function () {
  16980. return this._gl.createQuery();
  16981. };
  16982. /**
  16983. * Delete and release a webGL query
  16984. * @param query defines the query to delete
  16985. * @return the current engine
  16986. */
  16987. Engine.prototype.deleteQuery = function (query) {
  16988. this._gl.deleteQuery(query);
  16989. return this;
  16990. };
  16991. /**
  16992. * Check if a given query has resolved and got its value
  16993. * @param query defines the query to check
  16994. * @returns true if the query got its value
  16995. */
  16996. Engine.prototype.isQueryResultAvailable = function (query) {
  16997. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16998. };
  16999. /**
  17000. * Gets the value of a given query
  17001. * @param query defines the query to check
  17002. * @returns the value of the query
  17003. */
  17004. Engine.prototype.getQueryResult = function (query) {
  17005. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17006. };
  17007. /**
  17008. * Initiates an occlusion query
  17009. * @param algorithmType defines the algorithm to use
  17010. * @param query defines the query to use
  17011. * @returns the current engine
  17012. * @see http://doc.babylonjs.com/features/occlusionquery
  17013. */
  17014. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17015. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17016. this._gl.beginQuery(glAlgorithm, query);
  17017. return this;
  17018. };
  17019. /**
  17020. * Ends an occlusion query
  17021. * @see http://doc.babylonjs.com/features/occlusionquery
  17022. * @param algorithmType defines the algorithm to use
  17023. * @returns the current engine
  17024. */
  17025. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17026. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17027. this._gl.endQuery(glAlgorithm);
  17028. return this;
  17029. };
  17030. /* Time queries */
  17031. Engine.prototype._createTimeQuery = function () {
  17032. var timerQuery = this._caps.timerQuery;
  17033. if (timerQuery.createQueryEXT) {
  17034. return timerQuery.createQueryEXT();
  17035. }
  17036. return this.createQuery();
  17037. };
  17038. Engine.prototype._deleteTimeQuery = function (query) {
  17039. var timerQuery = this._caps.timerQuery;
  17040. if (timerQuery.deleteQueryEXT) {
  17041. timerQuery.deleteQueryEXT(query);
  17042. return;
  17043. }
  17044. this.deleteQuery(query);
  17045. };
  17046. Engine.prototype._getTimeQueryResult = function (query) {
  17047. var timerQuery = this._caps.timerQuery;
  17048. if (timerQuery.getQueryObjectEXT) {
  17049. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17050. }
  17051. return this.getQueryResult(query);
  17052. };
  17053. Engine.prototype._getTimeQueryAvailability = function (query) {
  17054. var timerQuery = this._caps.timerQuery;
  17055. if (timerQuery.getQueryObjectEXT) {
  17056. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17057. }
  17058. return this.isQueryResultAvailable(query);
  17059. };
  17060. /**
  17061. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17062. * Please note that only one query can be issued at a time
  17063. * @returns a time token used to track the time span
  17064. */
  17065. Engine.prototype.startTimeQuery = function () {
  17066. var timerQuery = this._caps.timerQuery;
  17067. if (!timerQuery) {
  17068. return null;
  17069. }
  17070. var token = new BABYLON._TimeToken();
  17071. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17072. if (this._caps.canUseTimestampForTimerQuery) {
  17073. token._startTimeQuery = this._createTimeQuery();
  17074. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17075. }
  17076. else {
  17077. if (this._currentNonTimestampToken) {
  17078. return this._currentNonTimestampToken;
  17079. }
  17080. token._timeElapsedQuery = this._createTimeQuery();
  17081. if (timerQuery.beginQueryEXT) {
  17082. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17083. }
  17084. else {
  17085. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17086. }
  17087. this._currentNonTimestampToken = token;
  17088. }
  17089. return token;
  17090. };
  17091. /**
  17092. * Ends a time query
  17093. * @param token defines the token used to measure the time span
  17094. * @returns the time spent (in ns)
  17095. */
  17096. Engine.prototype.endTimeQuery = function (token) {
  17097. var timerQuery = this._caps.timerQuery;
  17098. if (!timerQuery || !token) {
  17099. return -1;
  17100. }
  17101. if (this._caps.canUseTimestampForTimerQuery) {
  17102. if (!token._startTimeQuery) {
  17103. return -1;
  17104. }
  17105. if (!token._endTimeQuery) {
  17106. token._endTimeQuery = this._createTimeQuery();
  17107. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17108. }
  17109. }
  17110. else if (!token._timeElapsedQueryEnded) {
  17111. if (!token._timeElapsedQuery) {
  17112. return -1;
  17113. }
  17114. if (timerQuery.endQueryEXT) {
  17115. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17116. }
  17117. else {
  17118. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17119. }
  17120. token._timeElapsedQueryEnded = true;
  17121. }
  17122. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17123. var available = false;
  17124. if (token._endTimeQuery) {
  17125. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17126. }
  17127. else if (token._timeElapsedQuery) {
  17128. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17129. }
  17130. if (available && !disjoint) {
  17131. var result = 0;
  17132. if (this._caps.canUseTimestampForTimerQuery) {
  17133. if (!token._startTimeQuery || !token._endTimeQuery) {
  17134. return -1;
  17135. }
  17136. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17137. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17138. result = timeEnd - timeStart;
  17139. this._deleteTimeQuery(token._startTimeQuery);
  17140. this._deleteTimeQuery(token._endTimeQuery);
  17141. token._startTimeQuery = null;
  17142. token._endTimeQuery = null;
  17143. }
  17144. else {
  17145. if (!token._timeElapsedQuery) {
  17146. return -1;
  17147. }
  17148. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17149. this._deleteTimeQuery(token._timeElapsedQuery);
  17150. token._timeElapsedQuery = null;
  17151. token._timeElapsedQueryEnded = false;
  17152. this._currentNonTimestampToken = null;
  17153. }
  17154. return result;
  17155. }
  17156. return -1;
  17157. };
  17158. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17159. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17160. };
  17161. // Transform feedback
  17162. /**
  17163. * Creates a webGL transform feedback object
  17164. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17165. * @returns the webGL transform feedback object
  17166. */
  17167. Engine.prototype.createTransformFeedback = function () {
  17168. return this._gl.createTransformFeedback();
  17169. };
  17170. /**
  17171. * Delete a webGL transform feedback object
  17172. * @param value defines the webGL transform feedback object to delete
  17173. */
  17174. Engine.prototype.deleteTransformFeedback = function (value) {
  17175. this._gl.deleteTransformFeedback(value);
  17176. };
  17177. /**
  17178. * Bind a webGL transform feedback object to the webgl context
  17179. * @param value defines the webGL transform feedback object to bind
  17180. */
  17181. Engine.prototype.bindTransformFeedback = function (value) {
  17182. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17183. };
  17184. /**
  17185. * Begins a transform feedback operation
  17186. * @param usePoints defines if points or triangles must be used
  17187. */
  17188. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17189. if (usePoints === void 0) { usePoints = true; }
  17190. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17191. };
  17192. /**
  17193. * Ends a transform feedback operation
  17194. */
  17195. Engine.prototype.endTransformFeedback = function () {
  17196. this._gl.endTransformFeedback();
  17197. };
  17198. /**
  17199. * Specify the varyings to use with transform feedback
  17200. * @param program defines the associated webGL program
  17201. * @param value defines the list of strings representing the varying names
  17202. */
  17203. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17204. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17205. };
  17206. /**
  17207. * Bind a webGL buffer for a transform feedback operation
  17208. * @param value defines the webGL buffer to bind
  17209. */
  17210. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17211. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17212. };
  17213. /** @hidden */
  17214. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17215. var _this = this;
  17216. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17217. this._activeRequests.push(request);
  17218. request.onCompleteObservable.add(function (request) {
  17219. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17220. });
  17221. return request;
  17222. };
  17223. /** @hidden */
  17224. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17225. var _this = this;
  17226. return new Promise(function (resolve, reject) {
  17227. _this._loadFile(url, function (data) {
  17228. resolve(data);
  17229. }, undefined, database, useArrayBuffer, function (request, exception) {
  17230. reject(exception);
  17231. });
  17232. });
  17233. };
  17234. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17235. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17236. var onload = function (data) {
  17237. loadedFiles[index] = data;
  17238. loadedFiles._internalCount++;
  17239. if (loadedFiles._internalCount === 6) {
  17240. onfinish(loadedFiles);
  17241. }
  17242. };
  17243. var onerror = function (request, exception) {
  17244. if (onErrorCallBack && request) {
  17245. onErrorCallBack(request.status + " " + request.statusText, exception);
  17246. }
  17247. };
  17248. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17249. };
  17250. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17251. if (onError === void 0) { onError = null; }
  17252. var loadedFiles = [];
  17253. loadedFiles._internalCount = 0;
  17254. for (var index = 0; index < 6; index++) {
  17255. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17256. }
  17257. };
  17258. // Statics
  17259. /**
  17260. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17261. * @returns true if the engine can be created
  17262. * @ignorenaming
  17263. */
  17264. Engine.isSupported = function () {
  17265. try {
  17266. var tempcanvas = document.createElement("canvas");
  17267. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17268. return gl != null && !!window.WebGLRenderingContext;
  17269. }
  17270. catch (e) {
  17271. return false;
  17272. }
  17273. };
  17274. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17275. Engine.ExceptionList = [
  17276. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17277. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17278. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17279. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17280. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17281. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17282. ];
  17283. /** Gets the list of created engines */
  17284. Engine.Instances = new Array();
  17285. // Const statics
  17286. Engine._ALPHA_DISABLE = 0;
  17287. Engine._ALPHA_ADD = 1;
  17288. Engine._ALPHA_COMBINE = 2;
  17289. Engine._ALPHA_SUBTRACT = 3;
  17290. Engine._ALPHA_MULTIPLY = 4;
  17291. Engine._ALPHA_MAXIMIZED = 5;
  17292. Engine._ALPHA_ONEONE = 6;
  17293. Engine._ALPHA_PREMULTIPLIED = 7;
  17294. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17295. Engine._ALPHA_INTERPOLATE = 9;
  17296. Engine._ALPHA_SCREENMODE = 10;
  17297. Engine._DELAYLOADSTATE_NONE = 0;
  17298. Engine._DELAYLOADSTATE_LOADED = 1;
  17299. Engine._DELAYLOADSTATE_LOADING = 2;
  17300. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17301. Engine._TEXTUREFORMAT_ALPHA = 0;
  17302. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17303. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17304. Engine._TEXTUREFORMAT_RGB = 4;
  17305. Engine._TEXTUREFORMAT_RGBA = 5;
  17306. Engine._TEXTUREFORMAT_R32F = 6;
  17307. Engine._TEXTUREFORMAT_RG32F = 7;
  17308. Engine._TEXTUREFORMAT_RGB32F = 8;
  17309. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17310. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17311. Engine._TEXTURETYPE_FLOAT = 1;
  17312. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17313. // Depht or Stencil test Constants.
  17314. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17315. 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.
  17316. 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.
  17317. 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.
  17318. 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.
  17319. 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.
  17320. 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.
  17321. 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.
  17322. // Stencil Actions Constants.
  17323. Engine._KEEP = 0x1E00;
  17324. Engine._REPLACE = 0x1E01;
  17325. Engine._INCR = 0x1E02;
  17326. Engine._DECR = 0x1E03;
  17327. Engine._INVERT = 0x150A;
  17328. Engine._INCR_WRAP = 0x8507;
  17329. Engine._DECR_WRAP = 0x8508;
  17330. // Texture rescaling mode
  17331. Engine._SCALEMODE_FLOOR = 1;
  17332. Engine._SCALEMODE_NEAREST = 2;
  17333. Engine._SCALEMODE_CEILING = 3;
  17334. // Updatable statics so stick with vars here
  17335. /**
  17336. * Gets or sets the epsilon value used by collision engine
  17337. */
  17338. Engine.CollisionsEpsilon = 0.001;
  17339. /**
  17340. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17341. */
  17342. Engine.CodeRepository = "src/";
  17343. /**
  17344. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17345. */
  17346. Engine.ShadersRepository = "src/Shaders/";
  17347. return Engine;
  17348. }());
  17349. BABYLON.Engine = Engine;
  17350. })(BABYLON || (BABYLON = {}));
  17351. //# sourceMappingURL=babylon.engine.js.map
  17352. var BABYLON;
  17353. (function (BABYLON) {
  17354. /**
  17355. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17356. */
  17357. var Node = /** @class */ (function () {
  17358. /**
  17359. * Creates a new Node
  17360. * @param {string} name - the name and id to be given to this node
  17361. * @param {BABYLON.Scene} the scene this node will be added to
  17362. */
  17363. function Node(name, scene) {
  17364. if (scene === void 0) { scene = null; }
  17365. /**
  17366. * Gets or sets a string used to store user defined state for the node
  17367. */
  17368. this.state = "";
  17369. /**
  17370. * Gets or sets an object used to store user defined information for the node
  17371. */
  17372. this.metadata = null;
  17373. /**
  17374. * Gets or sets a boolean used to define if the node must be serialized
  17375. */
  17376. this.doNotSerialize = false;
  17377. /** @hidden */
  17378. this._isDisposed = false;
  17379. /**
  17380. * Gets a list of Animations associated with the node
  17381. */
  17382. this.animations = new Array();
  17383. this._ranges = {};
  17384. this._isEnabled = true;
  17385. this._isReady = true;
  17386. /** @hidden */
  17387. this._currentRenderId = -1;
  17388. this._parentRenderId = -1;
  17389. this._childRenderId = -1;
  17390. this._animationPropertiesOverride = null;
  17391. /**
  17392. * An event triggered when the mesh is disposed
  17393. */
  17394. this.onDisposeObservable = new BABYLON.Observable();
  17395. // Behaviors
  17396. this._behaviors = new Array();
  17397. this.name = name;
  17398. this.id = name;
  17399. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17400. this.uniqueId = this._scene.getUniqueId();
  17401. this._initCache();
  17402. }
  17403. /**
  17404. * Gets a boolean indicating if the node has been disposed
  17405. * @returns true if the node was disposed
  17406. */
  17407. Node.prototype.isDisposed = function () {
  17408. return this._isDisposed;
  17409. };
  17410. Object.defineProperty(Node.prototype, "parent", {
  17411. get: function () {
  17412. return this._parentNode;
  17413. },
  17414. /**
  17415. * Gets or sets the parent of the node
  17416. */
  17417. set: function (parent) {
  17418. if (this._parentNode === parent) {
  17419. return;
  17420. }
  17421. // Remove self from list of children of parent
  17422. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17423. var index = this._parentNode._children.indexOf(this);
  17424. if (index !== -1) {
  17425. this._parentNode._children.splice(index, 1);
  17426. }
  17427. }
  17428. // Store new parent
  17429. this._parentNode = parent;
  17430. // Add as child to new parent
  17431. if (this._parentNode) {
  17432. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17433. this._parentNode._children = new Array();
  17434. }
  17435. this._parentNode._children.push(this);
  17436. }
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17442. /**
  17443. * Gets or sets the animation properties override
  17444. */
  17445. get: function () {
  17446. if (!this._animationPropertiesOverride) {
  17447. return this._scene.animationPropertiesOverride;
  17448. }
  17449. return this._animationPropertiesOverride;
  17450. },
  17451. set: function (value) {
  17452. this._animationPropertiesOverride = value;
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. /**
  17458. * Gets a string idenfifying the name of the class
  17459. * @returns "Node" string
  17460. */
  17461. Node.prototype.getClassName = function () {
  17462. return "Node";
  17463. };
  17464. Object.defineProperty(Node.prototype, "onDispose", {
  17465. /**
  17466. * Sets a callback that will be raised when the node will be disposed
  17467. */
  17468. set: function (callback) {
  17469. if (this._onDisposeObserver) {
  17470. this.onDisposeObservable.remove(this._onDisposeObserver);
  17471. }
  17472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. /**
  17478. * Gets the scene of the node
  17479. * @returns a {BABYLON.Scene}
  17480. */
  17481. Node.prototype.getScene = function () {
  17482. return this._scene;
  17483. };
  17484. /**
  17485. * Gets the engine of the node
  17486. * @returns a {BABYLON.Engine}
  17487. */
  17488. Node.prototype.getEngine = function () {
  17489. return this._scene.getEngine();
  17490. };
  17491. /**
  17492. * Attach a behavior to the node
  17493. * @see http://doc.babylonjs.com/features/behaviour
  17494. * @param behavior defines the behavior to attach
  17495. * @returns the current Node
  17496. */
  17497. Node.prototype.addBehavior = function (behavior) {
  17498. var _this = this;
  17499. var index = this._behaviors.indexOf(behavior);
  17500. if (index !== -1) {
  17501. return this;
  17502. }
  17503. behavior.init();
  17504. if (this._scene.isLoading) {
  17505. // We defer the attach when the scene will be loaded
  17506. var observer = this._scene.onDataLoadedObservable.add(function () {
  17507. behavior.attach(_this);
  17508. setTimeout(function () {
  17509. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17510. _this._scene.onDataLoadedObservable.remove(observer);
  17511. }, 0);
  17512. });
  17513. }
  17514. else {
  17515. behavior.attach(this);
  17516. }
  17517. this._behaviors.push(behavior);
  17518. return this;
  17519. };
  17520. /**
  17521. * Remove an attached behavior
  17522. * @see http://doc.babylonjs.com/features/behaviour
  17523. * @param behavior defines the behavior to attach
  17524. * @returns the current Node
  17525. */
  17526. Node.prototype.removeBehavior = function (behavior) {
  17527. var index = this._behaviors.indexOf(behavior);
  17528. if (index === -1) {
  17529. return this;
  17530. }
  17531. this._behaviors[index].detach();
  17532. this._behaviors.splice(index, 1);
  17533. return this;
  17534. };
  17535. Object.defineProperty(Node.prototype, "behaviors", {
  17536. /**
  17537. * Gets the list of attached behaviors
  17538. * @see http://doc.babylonjs.com/features/behaviour
  17539. */
  17540. get: function () {
  17541. return this._behaviors;
  17542. },
  17543. enumerable: true,
  17544. configurable: true
  17545. });
  17546. /**
  17547. * Gets an attached behavior by name
  17548. * @param name defines the name of the behavior to look for
  17549. * @see http://doc.babylonjs.com/features/behaviour
  17550. * @returns null if behavior was not found else the requested behavior
  17551. */
  17552. Node.prototype.getBehaviorByName = function (name) {
  17553. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17554. var behavior = _a[_i];
  17555. if (behavior.name === name) {
  17556. return behavior;
  17557. }
  17558. }
  17559. return null;
  17560. };
  17561. /**
  17562. * Returns the world matrix of the node
  17563. * @returns a matrix containing the node's world matrix
  17564. */
  17565. Node.prototype.getWorldMatrix = function () {
  17566. return BABYLON.Matrix.Identity();
  17567. };
  17568. /** @hidden */
  17569. Node.prototype._getWorldMatrixDeterminant = function () {
  17570. return 1;
  17571. };
  17572. // override it in derived class if you add new variables to the cache
  17573. // and call the parent class method
  17574. /** @hidden */
  17575. Node.prototype._initCache = function () {
  17576. this._cache = {};
  17577. this._cache.parent = undefined;
  17578. };
  17579. /** @hidden */
  17580. Node.prototype.updateCache = function (force) {
  17581. if (!force && this.isSynchronized())
  17582. return;
  17583. this._cache.parent = this.parent;
  17584. this._updateCache();
  17585. };
  17586. // override it in derived class if you add new variables to the cache
  17587. // and call the parent class method if !ignoreParentClass
  17588. /** @hidden */
  17589. Node.prototype._updateCache = function (ignoreParentClass) {
  17590. };
  17591. // override it in derived class if you add new variables to the cache
  17592. /** @hidden */
  17593. Node.prototype._isSynchronized = function () {
  17594. return true;
  17595. };
  17596. /** @hidden */
  17597. Node.prototype._markSyncedWithParent = function () {
  17598. if (this.parent) {
  17599. this._parentRenderId = this.parent._childRenderId;
  17600. }
  17601. };
  17602. /** @hidden */
  17603. Node.prototype.isSynchronizedWithParent = function () {
  17604. if (!this.parent) {
  17605. return true;
  17606. }
  17607. if (this._parentRenderId !== this.parent._childRenderId) {
  17608. return false;
  17609. }
  17610. return this.parent.isSynchronized();
  17611. };
  17612. /** @hidden */
  17613. Node.prototype.isSynchronized = function (updateCache) {
  17614. var check = this.hasNewParent();
  17615. check = check || !this.isSynchronizedWithParent();
  17616. check = check || !this._isSynchronized();
  17617. if (updateCache)
  17618. this.updateCache(true);
  17619. return !check;
  17620. };
  17621. /** @hidden */
  17622. Node.prototype.hasNewParent = function (update) {
  17623. if (this._cache.parent === this.parent)
  17624. return false;
  17625. if (update)
  17626. this._cache.parent = this.parent;
  17627. return true;
  17628. };
  17629. /**
  17630. * Is this node ready to be used/rendered
  17631. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17632. * @return true if the node is ready
  17633. */
  17634. Node.prototype.isReady = function (completeCheck) {
  17635. if (completeCheck === void 0) { completeCheck = false; }
  17636. return this._isReady;
  17637. };
  17638. /**
  17639. * Is this node enabled?
  17640. * 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
  17641. * @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
  17642. * @return whether this node (and its parent) is enabled
  17643. */
  17644. Node.prototype.isEnabled = function (checkAncestors) {
  17645. if (checkAncestors === void 0) { checkAncestors = true; }
  17646. if (checkAncestors === false) {
  17647. return this._isEnabled;
  17648. }
  17649. if (this._isEnabled === false) {
  17650. return false;
  17651. }
  17652. if (this.parent !== undefined && this.parent !== null) {
  17653. return this.parent.isEnabled(checkAncestors);
  17654. }
  17655. return true;
  17656. };
  17657. /**
  17658. * Set the enabled state of this node
  17659. * @param value defines the new enabled state
  17660. */
  17661. Node.prototype.setEnabled = function (value) {
  17662. this._isEnabled = value;
  17663. };
  17664. /**
  17665. * Is this node a descendant of the given node?
  17666. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17667. * @param ancestor defines the parent node to inspect
  17668. * @returns a boolean indicating if this node is a descendant of the given node
  17669. */
  17670. Node.prototype.isDescendantOf = function (ancestor) {
  17671. if (this.parent) {
  17672. if (this.parent === ancestor) {
  17673. return true;
  17674. }
  17675. return this.parent.isDescendantOf(ancestor);
  17676. }
  17677. return false;
  17678. };
  17679. /** @hidden */
  17680. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17681. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17682. if (!this._children) {
  17683. return;
  17684. }
  17685. for (var index = 0; index < this._children.length; index++) {
  17686. var item = this._children[index];
  17687. if (!predicate || predicate(item)) {
  17688. results.push(item);
  17689. }
  17690. if (!directDescendantsOnly) {
  17691. item._getDescendants(results, false, predicate);
  17692. }
  17693. }
  17694. };
  17695. /**
  17696. * Will return all nodes that have this node as ascendant
  17697. * @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
  17698. * @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
  17699. * @return all children nodes of all types
  17700. */
  17701. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17702. var results = new Array();
  17703. this._getDescendants(results, directDescendantsOnly, predicate);
  17704. return results;
  17705. };
  17706. /**
  17707. * Get all child-meshes of this node
  17708. * @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
  17709. * @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
  17710. * @returns an array of {BABYLON.AbstractMesh}
  17711. */
  17712. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17713. var results = [];
  17714. this._getDescendants(results, directDescendantsOnly, function (node) {
  17715. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17716. });
  17717. return results;
  17718. };
  17719. /**
  17720. * Get all child-transformNodes of this node
  17721. * @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
  17722. * @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
  17723. * @returns an array of {BABYLON.TransformNode}
  17724. */
  17725. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17726. var results = [];
  17727. this._getDescendants(results, directDescendantsOnly, function (node) {
  17728. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17729. });
  17730. return results;
  17731. };
  17732. /**
  17733. * Get all direct children of this node
  17734. * @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
  17735. * @returns an array of {BABYLON.Node}
  17736. */
  17737. Node.prototype.getChildren = function (predicate) {
  17738. return this.getDescendants(true, predicate);
  17739. };
  17740. /** @hidden */
  17741. Node.prototype._setReady = function (state) {
  17742. if (state === this._isReady) {
  17743. return;
  17744. }
  17745. if (!state) {
  17746. this._isReady = false;
  17747. return;
  17748. }
  17749. if (this.onReady) {
  17750. this.onReady(this);
  17751. }
  17752. this._isReady = true;
  17753. };
  17754. /**
  17755. * Get an animation by name
  17756. * @param name defines the name of the animation to look for
  17757. * @returns null if not found else the requested animation
  17758. */
  17759. Node.prototype.getAnimationByName = function (name) {
  17760. for (var i = 0; i < this.animations.length; i++) {
  17761. var animation = this.animations[i];
  17762. if (animation.name === name) {
  17763. return animation;
  17764. }
  17765. }
  17766. return null;
  17767. };
  17768. /**
  17769. * Creates an animation range for this node
  17770. * @param name defines the name of the range
  17771. * @param from defines the starting key
  17772. * @param to defines the end key
  17773. */
  17774. Node.prototype.createAnimationRange = function (name, from, to) {
  17775. // check name not already in use
  17776. if (!this._ranges[name]) {
  17777. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17778. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17779. if (this.animations[i]) {
  17780. this.animations[i].createRange(name, from, to);
  17781. }
  17782. }
  17783. }
  17784. };
  17785. /**
  17786. * Delete a specific animation range
  17787. * @param name defines the name of the range to delete
  17788. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17789. */
  17790. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17791. if (deleteFrames === void 0) { deleteFrames = true; }
  17792. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17793. if (this.animations[i]) {
  17794. this.animations[i].deleteRange(name, deleteFrames);
  17795. }
  17796. }
  17797. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17798. };
  17799. /**
  17800. * Get an animation range by name
  17801. * @param name defines the name of the animation range to look for
  17802. * @returns null if not found else the requested animation range
  17803. */
  17804. Node.prototype.getAnimationRange = function (name) {
  17805. return this._ranges[name];
  17806. };
  17807. /**
  17808. * Will start the animation sequence
  17809. * @param name defines the range frames for animation sequence
  17810. * @param loop defines if the animation should loop (false by default)
  17811. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17812. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17813. * @returns the object created for this animation. If range does not exist, it will return null
  17814. */
  17815. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17816. var range = this.getAnimationRange(name);
  17817. if (!range) {
  17818. return null;
  17819. }
  17820. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17821. };
  17822. /**
  17823. * Serialize animation ranges into a JSON compatible object
  17824. * @returns serialization object
  17825. */
  17826. Node.prototype.serializeAnimationRanges = function () {
  17827. var serializationRanges = [];
  17828. for (var name in this._ranges) {
  17829. var localRange = this._ranges[name];
  17830. if (!localRange) {
  17831. continue;
  17832. }
  17833. var range = {};
  17834. range.name = name;
  17835. range.from = localRange.from;
  17836. range.to = localRange.to;
  17837. serializationRanges.push(range);
  17838. }
  17839. return serializationRanges;
  17840. };
  17841. /**
  17842. * Computes the world matrix of the node
  17843. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17844. * @returns the world matrix
  17845. */
  17846. Node.prototype.computeWorldMatrix = function (force) {
  17847. return BABYLON.Matrix.Identity();
  17848. };
  17849. /**
  17850. * Releases resources associated with this node.
  17851. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17852. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17853. */
  17854. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17855. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17856. if (!doNotRecurse) {
  17857. var nodes = this.getDescendants(true);
  17858. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17859. var node = nodes_1[_i];
  17860. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17861. }
  17862. }
  17863. else {
  17864. var transformNodes = this.getChildTransformNodes(true);
  17865. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17866. var transformNode = transformNodes_1[_a];
  17867. transformNode.parent = null;
  17868. transformNode.computeWorldMatrix(true);
  17869. }
  17870. }
  17871. this.parent = null;
  17872. // Callback
  17873. this.onDisposeObservable.notifyObservers(this);
  17874. this.onDisposeObservable.clear();
  17875. // Behaviors
  17876. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17877. var behavior = _c[_b];
  17878. behavior.detach();
  17879. }
  17880. this._behaviors = [];
  17881. this._isDisposed = true;
  17882. };
  17883. /**
  17884. * Parse animation range data from a serialization object and store them into a given node
  17885. * @param node defines where to store the animation ranges
  17886. * @param parsedNode defines the serialization object to read data from
  17887. * @param scene defines the hosting scene
  17888. */
  17889. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17890. if (parsedNode.ranges) {
  17891. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17892. var data = parsedNode.ranges[index];
  17893. node.createAnimationRange(data.name, data.from, data.to);
  17894. }
  17895. }
  17896. };
  17897. __decorate([
  17898. BABYLON.serialize()
  17899. ], Node.prototype, "name", void 0);
  17900. __decorate([
  17901. BABYLON.serialize()
  17902. ], Node.prototype, "id", void 0);
  17903. __decorate([
  17904. BABYLON.serialize()
  17905. ], Node.prototype, "uniqueId", void 0);
  17906. __decorate([
  17907. BABYLON.serialize()
  17908. ], Node.prototype, "state", void 0);
  17909. __decorate([
  17910. BABYLON.serialize()
  17911. ], Node.prototype, "metadata", void 0);
  17912. return Node;
  17913. }());
  17914. BABYLON.Node = Node;
  17915. })(BABYLON || (BABYLON = {}));
  17916. //# sourceMappingURL=babylon.node.js.map
  17917. var BABYLON;
  17918. (function (BABYLON) {
  17919. var BoundingSphere = /** @class */ (function () {
  17920. /**
  17921. * Creates a new bounding sphere
  17922. * @param min defines the minimum vector (in local space)
  17923. * @param max defines the maximum vector (in local space)
  17924. */
  17925. function BoundingSphere(min, max) {
  17926. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17927. this.reConstruct(min, max);
  17928. }
  17929. /**
  17930. * Recreates the entire bounding sphere from scratch
  17931. * @param min defines the new minimum vector (in local space)
  17932. * @param max defines the new maximum vector (in local space)
  17933. */
  17934. BoundingSphere.prototype.reConstruct = function (min, max) {
  17935. this.minimum = min.clone();
  17936. this.maximum = max.clone();
  17937. var distance = BABYLON.Vector3.Distance(min, max);
  17938. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17939. this.radius = distance * 0.5;
  17940. this.centerWorld = BABYLON.Vector3.Zero();
  17941. this._update(BABYLON.Matrix.Identity());
  17942. };
  17943. // Methods
  17944. BoundingSphere.prototype._update = function (world) {
  17945. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17946. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17947. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17948. };
  17949. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17950. for (var i = 0; i < 6; i++) {
  17951. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17952. return false;
  17953. }
  17954. return true;
  17955. };
  17956. BoundingSphere.prototype.intersectsPoint = function (point) {
  17957. var x = this.centerWorld.x - point.x;
  17958. var y = this.centerWorld.y - point.y;
  17959. var z = this.centerWorld.z - point.z;
  17960. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17961. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17962. return false;
  17963. return true;
  17964. };
  17965. // Statics
  17966. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17967. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17968. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17969. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17970. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17971. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17972. return false;
  17973. return true;
  17974. };
  17975. return BoundingSphere;
  17976. }());
  17977. BABYLON.BoundingSphere = BoundingSphere;
  17978. })(BABYLON || (BABYLON = {}));
  17979. //# sourceMappingURL=babylon.boundingSphere.js.map
  17980. var BABYLON;
  17981. (function (BABYLON) {
  17982. var BoundingBox = /** @class */ (function () {
  17983. /**
  17984. * Creates a new bounding box
  17985. * @param min defines the minimum vector (in local space)
  17986. * @param max defines the maximum vector (in local space)
  17987. */
  17988. function BoundingBox(min, max) {
  17989. this.vectorsWorld = new Array();
  17990. this.reConstruct(min, max);
  17991. }
  17992. // Methods
  17993. /**
  17994. * Recreates the entire bounding box from scratch
  17995. * @param min defines the new minimum vector (in local space)
  17996. * @param max defines the new maximum vector (in local space)
  17997. */
  17998. BoundingBox.prototype.reConstruct = function (min, max) {
  17999. this.minimum = min.clone();
  18000. this.maximum = max.clone();
  18001. // Bounding vectors
  18002. this.vectors = new Array();
  18003. this.vectors.push(this.minimum.clone());
  18004. this.vectors.push(this.maximum.clone());
  18005. this.vectors.push(this.minimum.clone());
  18006. this.vectors[2].x = this.maximum.x;
  18007. this.vectors.push(this.minimum.clone());
  18008. this.vectors[3].y = this.maximum.y;
  18009. this.vectors.push(this.minimum.clone());
  18010. this.vectors[4].z = this.maximum.z;
  18011. this.vectors.push(this.maximum.clone());
  18012. this.vectors[5].z = this.minimum.z;
  18013. this.vectors.push(this.maximum.clone());
  18014. this.vectors[6].x = this.minimum.x;
  18015. this.vectors.push(this.maximum.clone());
  18016. this.vectors[7].y = this.minimum.y;
  18017. // OBB
  18018. this.center = this.maximum.add(this.minimum).scale(0.5);
  18019. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18020. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18021. // World
  18022. for (var index = 0; index < this.vectors.length; index++) {
  18023. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18024. }
  18025. this.minimumWorld = BABYLON.Vector3.Zero();
  18026. this.maximumWorld = BABYLON.Vector3.Zero();
  18027. this.centerWorld = BABYLON.Vector3.Zero();
  18028. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18029. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18030. };
  18031. BoundingBox.prototype.getWorldMatrix = function () {
  18032. return this._worldMatrix;
  18033. };
  18034. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18035. this._worldMatrix.copyFrom(matrix);
  18036. return this;
  18037. };
  18038. BoundingBox.prototype._update = function (world) {
  18039. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18040. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18041. for (var index = 0; index < this.vectors.length; index++) {
  18042. var v = this.vectorsWorld[index];
  18043. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18044. if (v.x < this.minimumWorld.x)
  18045. this.minimumWorld.x = v.x;
  18046. if (v.y < this.minimumWorld.y)
  18047. this.minimumWorld.y = v.y;
  18048. if (v.z < this.minimumWorld.z)
  18049. this.minimumWorld.z = v.z;
  18050. if (v.x > this.maximumWorld.x)
  18051. this.maximumWorld.x = v.x;
  18052. if (v.y > this.maximumWorld.y)
  18053. this.maximumWorld.y = v.y;
  18054. if (v.z > this.maximumWorld.z)
  18055. this.maximumWorld.z = v.z;
  18056. }
  18057. // Extend
  18058. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18059. this.extendSizeWorld.scaleInPlace(0.5);
  18060. // OBB
  18061. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18062. this.centerWorld.scaleInPlace(0.5);
  18063. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18064. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18065. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18066. this._worldMatrix = world;
  18067. };
  18068. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18069. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18070. };
  18071. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18072. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18073. };
  18074. BoundingBox.prototype.intersectsPoint = function (point) {
  18075. var delta = -BABYLON.Epsilon;
  18076. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18077. return false;
  18078. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18079. return false;
  18080. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18081. return false;
  18082. return true;
  18083. };
  18084. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18085. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18086. };
  18087. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18088. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18089. return false;
  18090. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18091. return false;
  18092. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18093. return false;
  18094. return true;
  18095. };
  18096. // Statics
  18097. BoundingBox.Intersects = function (box0, box1) {
  18098. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18099. return false;
  18100. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18101. return false;
  18102. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18103. return false;
  18104. return true;
  18105. };
  18106. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18107. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18108. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18109. return (num <= (sphereRadius * sphereRadius));
  18110. };
  18111. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18112. for (var p = 0; p < 6; p++) {
  18113. for (var i = 0; i < 8; i++) {
  18114. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18115. return false;
  18116. }
  18117. }
  18118. }
  18119. return true;
  18120. };
  18121. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18122. for (var p = 0; p < 6; p++) {
  18123. var inCount = 8;
  18124. for (var i = 0; i < 8; i++) {
  18125. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18126. --inCount;
  18127. }
  18128. else {
  18129. break;
  18130. }
  18131. }
  18132. if (inCount === 0)
  18133. return false;
  18134. }
  18135. return true;
  18136. };
  18137. return BoundingBox;
  18138. }());
  18139. BABYLON.BoundingBox = BoundingBox;
  18140. })(BABYLON || (BABYLON = {}));
  18141. //# sourceMappingURL=babylon.boundingBox.js.map
  18142. var BABYLON;
  18143. (function (BABYLON) {
  18144. var computeBoxExtents = function (axis, box) {
  18145. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18146. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18147. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18148. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18149. var r = r0 + r1 + r2;
  18150. return {
  18151. min: p - r,
  18152. max: p + r
  18153. };
  18154. };
  18155. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18156. var axisOverlap = function (axis, box0, box1) {
  18157. var result0 = computeBoxExtents(axis, box0);
  18158. var result1 = computeBoxExtents(axis, box1);
  18159. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18160. };
  18161. var BoundingInfo = /** @class */ (function () {
  18162. function BoundingInfo(minimum, maximum) {
  18163. this.minimum = minimum;
  18164. this.maximum = maximum;
  18165. this._isLocked = false;
  18166. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18167. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18168. }
  18169. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18170. get: function () {
  18171. return this._isLocked;
  18172. },
  18173. set: function (value) {
  18174. this._isLocked = value;
  18175. },
  18176. enumerable: true,
  18177. configurable: true
  18178. });
  18179. // Methods
  18180. BoundingInfo.prototype.update = function (world) {
  18181. if (this._isLocked) {
  18182. return;
  18183. }
  18184. this.boundingBox._update(world);
  18185. this.boundingSphere._update(world);
  18186. };
  18187. /**
  18188. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18189. * @param center New center of the bounding info
  18190. * @param extend New extend of the bounding info
  18191. */
  18192. BoundingInfo.prototype.centerOn = function (center, extend) {
  18193. this.minimum = center.subtract(extend);
  18194. this.maximum = center.add(extend);
  18195. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18196. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18197. return this;
  18198. };
  18199. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18200. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18201. return false;
  18202. return this.boundingBox.isInFrustum(frustumPlanes);
  18203. };
  18204. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18205. /**
  18206. * Gets the world distance between the min and max points of the bounding box
  18207. */
  18208. get: function () {
  18209. var boundingBox = this.boundingBox;
  18210. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18211. return size.length();
  18212. },
  18213. enumerable: true,
  18214. configurable: true
  18215. });
  18216. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18217. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18218. };
  18219. BoundingInfo.prototype._checkCollision = function (collider) {
  18220. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18221. };
  18222. BoundingInfo.prototype.intersectsPoint = function (point) {
  18223. if (!this.boundingSphere.centerWorld) {
  18224. return false;
  18225. }
  18226. if (!this.boundingSphere.intersectsPoint(point)) {
  18227. return false;
  18228. }
  18229. if (!this.boundingBox.intersectsPoint(point)) {
  18230. return false;
  18231. }
  18232. return true;
  18233. };
  18234. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18235. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18236. return false;
  18237. }
  18238. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18239. return false;
  18240. }
  18241. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18242. return false;
  18243. }
  18244. if (!precise) {
  18245. return true;
  18246. }
  18247. var box0 = this.boundingBox;
  18248. var box1 = boundingInfo.boundingBox;
  18249. if (!axisOverlap(box0.directions[0], box0, box1))
  18250. return false;
  18251. if (!axisOverlap(box0.directions[1], box0, box1))
  18252. return false;
  18253. if (!axisOverlap(box0.directions[2], box0, box1))
  18254. return false;
  18255. if (!axisOverlap(box1.directions[0], box0, box1))
  18256. return false;
  18257. if (!axisOverlap(box1.directions[1], box0, box1))
  18258. return false;
  18259. if (!axisOverlap(box1.directions[2], box0, box1))
  18260. return false;
  18261. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18262. return false;
  18263. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18264. return false;
  18265. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18266. return false;
  18267. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18268. return false;
  18269. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18270. return false;
  18271. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18272. return false;
  18273. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18274. return false;
  18275. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18276. return false;
  18277. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18278. return false;
  18279. return true;
  18280. };
  18281. return BoundingInfo;
  18282. }());
  18283. BABYLON.BoundingInfo = BoundingInfo;
  18284. })(BABYLON || (BABYLON = {}));
  18285. //# sourceMappingURL=babylon.boundingInfo.js.map
  18286. var BABYLON;
  18287. (function (BABYLON) {
  18288. var TransformNode = /** @class */ (function (_super) {
  18289. __extends(TransformNode, _super);
  18290. function TransformNode(name, scene, isPure) {
  18291. if (scene === void 0) { scene = null; }
  18292. if (isPure === void 0) { isPure = true; }
  18293. var _this = _super.call(this, name, scene) || this;
  18294. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18295. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18296. _this._up = new BABYLON.Vector3(0, 1, 0);
  18297. _this._right = new BABYLON.Vector3(1, 0, 0);
  18298. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18299. // Properties
  18300. _this._rotation = BABYLON.Vector3.Zero();
  18301. _this._scaling = BABYLON.Vector3.One();
  18302. _this._isDirty = false;
  18303. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18304. _this.scalingDeterminant = 1;
  18305. _this.infiniteDistance = false;
  18306. _this.position = BABYLON.Vector3.Zero();
  18307. _this._localWorld = BABYLON.Matrix.Zero();
  18308. _this._worldMatrix = BABYLON.Matrix.Zero();
  18309. _this._worldMatrixDeterminant = 0;
  18310. _this._absolutePosition = BABYLON.Vector3.Zero();
  18311. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18312. _this._postMultiplyPivotMatrix = false;
  18313. _this._isWorldMatrixFrozen = false;
  18314. /**
  18315. * An event triggered after the world matrix is updated
  18316. */
  18317. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18318. _this._nonUniformScaling = false;
  18319. if (isPure) {
  18320. _this.getScene().addTransformNode(_this);
  18321. }
  18322. return _this;
  18323. }
  18324. /**
  18325. * Gets a string idenfifying the name of the class
  18326. * @returns "TransformNode" string
  18327. */
  18328. TransformNode.prototype.getClassName = function () {
  18329. return "TransformNode";
  18330. };
  18331. Object.defineProperty(TransformNode.prototype, "rotation", {
  18332. /**
  18333. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18334. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18335. * Default : (0.0, 0.0, 0.0)
  18336. */
  18337. get: function () {
  18338. return this._rotation;
  18339. },
  18340. set: function (newRotation) {
  18341. this._rotation = newRotation;
  18342. },
  18343. enumerable: true,
  18344. configurable: true
  18345. });
  18346. Object.defineProperty(TransformNode.prototype, "scaling", {
  18347. /**
  18348. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18349. * Default : (1.0, 1.0, 1.0)
  18350. */
  18351. get: function () {
  18352. return this._scaling;
  18353. },
  18354. /**
  18355. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18356. * Default : (1.0, 1.0, 1.0)
  18357. */
  18358. set: function (newScaling) {
  18359. this._scaling = newScaling;
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18365. /**
  18366. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18367. * It's null by default.
  18368. * 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)
  18369. */
  18370. get: function () {
  18371. return this._rotationQuaternion;
  18372. },
  18373. set: function (quaternion) {
  18374. this._rotationQuaternion = quaternion;
  18375. //reset the rotation vector.
  18376. if (quaternion && this.rotation.length()) {
  18377. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18378. }
  18379. },
  18380. enumerable: true,
  18381. configurable: true
  18382. });
  18383. Object.defineProperty(TransformNode.prototype, "forward", {
  18384. /**
  18385. * The forward direction of that transform in world space.
  18386. */
  18387. get: function () {
  18388. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18389. },
  18390. enumerable: true,
  18391. configurable: true
  18392. });
  18393. Object.defineProperty(TransformNode.prototype, "up", {
  18394. /**
  18395. * The up direction of that transform in world space.
  18396. */
  18397. get: function () {
  18398. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18399. },
  18400. enumerable: true,
  18401. configurable: true
  18402. });
  18403. Object.defineProperty(TransformNode.prototype, "right", {
  18404. /**
  18405. * The right direction of that transform in world space.
  18406. */
  18407. get: function () {
  18408. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18409. },
  18410. enumerable: true,
  18411. configurable: true
  18412. });
  18413. /**
  18414. * Returns the latest update of the World matrix
  18415. * Returns a Matrix.
  18416. */
  18417. TransformNode.prototype.getWorldMatrix = function () {
  18418. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18419. this.computeWorldMatrix();
  18420. }
  18421. return this._worldMatrix;
  18422. };
  18423. /** @hidden */
  18424. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18425. return this._worldMatrixDeterminant;
  18426. };
  18427. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18428. /**
  18429. * Returns directly the latest state of the mesh World matrix.
  18430. * A Matrix is returned.
  18431. */
  18432. get: function () {
  18433. return this._worldMatrix;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. /**
  18439. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18440. * Returns the TransformNode.
  18441. */
  18442. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18443. this._poseMatrix.copyFrom(matrix);
  18444. return this;
  18445. };
  18446. /**
  18447. * Returns the mesh Pose matrix.
  18448. * Returned object : Matrix
  18449. */
  18450. TransformNode.prototype.getPoseMatrix = function () {
  18451. return this._poseMatrix;
  18452. };
  18453. TransformNode.prototype._isSynchronized = function () {
  18454. if (this._isDirty) {
  18455. return false;
  18456. }
  18457. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18458. return false;
  18459. if (this._cache.pivotMatrixUpdated) {
  18460. return false;
  18461. }
  18462. if (this.infiniteDistance) {
  18463. return false;
  18464. }
  18465. if (!this._cache.position.equals(this.position))
  18466. return false;
  18467. if (this.rotationQuaternion) {
  18468. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18469. return false;
  18470. }
  18471. if (!this._cache.rotation.equals(this.rotation))
  18472. return false;
  18473. if (!this._cache.scaling.equals(this.scaling))
  18474. return false;
  18475. return true;
  18476. };
  18477. TransformNode.prototype._initCache = function () {
  18478. _super.prototype._initCache.call(this);
  18479. this._cache.localMatrixUpdated = false;
  18480. this._cache.position = BABYLON.Vector3.Zero();
  18481. this._cache.scaling = BABYLON.Vector3.Zero();
  18482. this._cache.rotation = BABYLON.Vector3.Zero();
  18483. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18484. this._cache.billboardMode = -1;
  18485. };
  18486. TransformNode.prototype.markAsDirty = function (property) {
  18487. if (property === "rotation") {
  18488. this.rotationQuaternion = null;
  18489. }
  18490. this._currentRenderId = Number.MAX_VALUE;
  18491. this._isDirty = true;
  18492. return this;
  18493. };
  18494. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18495. /**
  18496. * Returns the current mesh absolute position.
  18497. * Retuns a Vector3.
  18498. */
  18499. get: function () {
  18500. return this._absolutePosition;
  18501. },
  18502. enumerable: true,
  18503. configurable: true
  18504. });
  18505. /**
  18506. * Sets a new matrix to apply before all other transformation
  18507. * @param matrix defines the transform matrix
  18508. * @returns the current TransformNode
  18509. */
  18510. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18511. return this.setPivotMatrix(matrix, false);
  18512. };
  18513. /**
  18514. * Sets a new pivot matrix to the current node
  18515. * @param matrix defines the new pivot matrix to use
  18516. * @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
  18517. * @returns the current TransformNode
  18518. */
  18519. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18520. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18521. this._pivotMatrix = matrix.clone();
  18522. this._cache.pivotMatrixUpdated = true;
  18523. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18524. if (this._postMultiplyPivotMatrix) {
  18525. if (!this._pivotMatrixInverse) {
  18526. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18527. }
  18528. else {
  18529. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18530. }
  18531. }
  18532. return this;
  18533. };
  18534. /**
  18535. * Returns the mesh pivot matrix.
  18536. * Default : Identity.
  18537. * A Matrix is returned.
  18538. */
  18539. TransformNode.prototype.getPivotMatrix = function () {
  18540. return this._pivotMatrix;
  18541. };
  18542. /**
  18543. * Prevents the World matrix to be computed any longer.
  18544. * Returns the TransformNode.
  18545. */
  18546. TransformNode.prototype.freezeWorldMatrix = function () {
  18547. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18548. this.computeWorldMatrix(true);
  18549. this._isWorldMatrixFrozen = true;
  18550. return this;
  18551. };
  18552. /**
  18553. * Allows back the World matrix computation.
  18554. * Returns the TransformNode.
  18555. */
  18556. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18557. this._isWorldMatrixFrozen = false;
  18558. this.computeWorldMatrix(true);
  18559. return this;
  18560. };
  18561. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18562. /**
  18563. * True if the World matrix has been frozen.
  18564. * Returns a boolean.
  18565. */
  18566. get: function () {
  18567. return this._isWorldMatrixFrozen;
  18568. },
  18569. enumerable: true,
  18570. configurable: true
  18571. });
  18572. /**
  18573. * Retuns the mesh absolute position in the World.
  18574. * Returns a Vector3.
  18575. */
  18576. TransformNode.prototype.getAbsolutePosition = function () {
  18577. this.computeWorldMatrix();
  18578. return this._absolutePosition;
  18579. };
  18580. /**
  18581. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18582. * Returns the TransformNode.
  18583. */
  18584. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18585. if (!absolutePosition) {
  18586. return this;
  18587. }
  18588. var absolutePositionX;
  18589. var absolutePositionY;
  18590. var absolutePositionZ;
  18591. if (absolutePosition.x === undefined) {
  18592. if (arguments.length < 3) {
  18593. return this;
  18594. }
  18595. absolutePositionX = arguments[0];
  18596. absolutePositionY = arguments[1];
  18597. absolutePositionZ = arguments[2];
  18598. }
  18599. else {
  18600. absolutePositionX = absolutePosition.x;
  18601. absolutePositionY = absolutePosition.y;
  18602. absolutePositionZ = absolutePosition.z;
  18603. }
  18604. if (this.parent) {
  18605. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18606. invertParentWorldMatrix.invert();
  18607. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18608. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18609. }
  18610. else {
  18611. this.position.x = absolutePositionX;
  18612. this.position.y = absolutePositionY;
  18613. this.position.z = absolutePositionZ;
  18614. }
  18615. return this;
  18616. };
  18617. /**
  18618. * Sets the mesh position in its local space.
  18619. * Returns the TransformNode.
  18620. */
  18621. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18622. this.computeWorldMatrix();
  18623. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18624. return this;
  18625. };
  18626. /**
  18627. * Returns the mesh position in the local space from the current World matrix values.
  18628. * Returns a new Vector3.
  18629. */
  18630. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18631. this.computeWorldMatrix();
  18632. var invLocalWorldMatrix = this._localWorld.clone();
  18633. invLocalWorldMatrix.invert();
  18634. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18635. };
  18636. /**
  18637. * Translates the mesh along the passed Vector3 in its local space.
  18638. * Returns the TransformNode.
  18639. */
  18640. TransformNode.prototype.locallyTranslate = function (vector3) {
  18641. this.computeWorldMatrix(true);
  18642. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18643. return this;
  18644. };
  18645. /**
  18646. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18647. * @param targetPoint the position (must be in same space as current mesh) to look at
  18648. * @param yawCor optional yaw (y-axis) correction in radians
  18649. * @param pitchCor optional pitch (x-axis) correction in radians
  18650. * @param rollCor optional roll (z-axis) correction in radians
  18651. * @param space the choosen space of the target
  18652. * @returns the TransformNode.
  18653. */
  18654. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18655. if (yawCor === void 0) { yawCor = 0; }
  18656. if (pitchCor === void 0) { pitchCor = 0; }
  18657. if (rollCor === void 0) { rollCor = 0; }
  18658. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18659. var dv = TransformNode._lookAtVectorCache;
  18660. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18661. targetPoint.subtractToRef(pos, dv);
  18662. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18663. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18664. var pitch = Math.atan2(dv.y, len);
  18665. if (this.rotationQuaternion) {
  18666. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18667. }
  18668. else {
  18669. this.rotation.x = pitch + pitchCor;
  18670. this.rotation.y = yaw + yawCor;
  18671. this.rotation.z = rollCor;
  18672. }
  18673. return this;
  18674. };
  18675. /**
  18676. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18677. * This Vector3 is expressed in the World space.
  18678. */
  18679. TransformNode.prototype.getDirection = function (localAxis) {
  18680. var result = BABYLON.Vector3.Zero();
  18681. this.getDirectionToRef(localAxis, result);
  18682. return result;
  18683. };
  18684. /**
  18685. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18686. * localAxis is expressed in the mesh local space.
  18687. * result is computed in the Wordl space from the mesh World matrix.
  18688. * Returns the TransformNode.
  18689. */
  18690. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18691. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18692. return this;
  18693. };
  18694. /**
  18695. * Sets a new pivot point to the current node
  18696. * @param point defines the new pivot point to use
  18697. * @param space defines if the point is in world or local space (local by default)
  18698. * @returns the current TransformNode
  18699. */
  18700. TransformNode.prototype.setPivotPoint = function (point, space) {
  18701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18702. if (this.getScene().getRenderId() == 0) {
  18703. this.computeWorldMatrix(true);
  18704. }
  18705. var wm = this.getWorldMatrix();
  18706. if (space == BABYLON.Space.WORLD) {
  18707. var tmat = BABYLON.Tmp.Matrix[0];
  18708. wm.invertToRef(tmat);
  18709. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18710. }
  18711. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18712. };
  18713. /**
  18714. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18715. */
  18716. TransformNode.prototype.getPivotPoint = function () {
  18717. var point = BABYLON.Vector3.Zero();
  18718. this.getPivotPointToRef(point);
  18719. return point;
  18720. };
  18721. /**
  18722. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18723. * Returns the TransformNode.
  18724. */
  18725. TransformNode.prototype.getPivotPointToRef = function (result) {
  18726. result.x = -this._pivotMatrix.m[12];
  18727. result.y = -this._pivotMatrix.m[13];
  18728. result.z = -this._pivotMatrix.m[14];
  18729. return this;
  18730. };
  18731. /**
  18732. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18733. */
  18734. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18735. var point = BABYLON.Vector3.Zero();
  18736. this.getAbsolutePivotPointToRef(point);
  18737. return point;
  18738. };
  18739. /**
  18740. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18741. * Returns the TransformNode.
  18742. */
  18743. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18744. result.x = this._pivotMatrix.m[12];
  18745. result.y = this._pivotMatrix.m[13];
  18746. result.z = this._pivotMatrix.m[14];
  18747. this.getPivotPointToRef(result);
  18748. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18749. return this;
  18750. };
  18751. /**
  18752. * Defines the passed node as the parent of the current node.
  18753. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18754. * Returns the TransformNode.
  18755. */
  18756. TransformNode.prototype.setParent = function (node) {
  18757. if (node === null) {
  18758. var rotation = BABYLON.Tmp.Quaternion[0];
  18759. var position = BABYLON.Tmp.Vector3[0];
  18760. var scale = BABYLON.Tmp.Vector3[1];
  18761. if (this.parent && this.parent.computeWorldMatrix) {
  18762. this.parent.computeWorldMatrix(true);
  18763. }
  18764. this.computeWorldMatrix(true);
  18765. this.getWorldMatrix().decompose(scale, rotation, position);
  18766. if (this.rotationQuaternion) {
  18767. this.rotationQuaternion.copyFrom(rotation);
  18768. }
  18769. else {
  18770. rotation.toEulerAnglesToRef(this.rotation);
  18771. }
  18772. this.scaling.x = scale.x;
  18773. this.scaling.y = scale.y;
  18774. this.scaling.z = scale.z;
  18775. this.position.x = position.x;
  18776. this.position.y = position.y;
  18777. this.position.z = position.z;
  18778. }
  18779. else {
  18780. var rotation = BABYLON.Tmp.Quaternion[0];
  18781. var position = BABYLON.Tmp.Vector3[0];
  18782. var scale = BABYLON.Tmp.Vector3[1];
  18783. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18784. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18785. this.computeWorldMatrix(true);
  18786. node.computeWorldMatrix(true);
  18787. node.getWorldMatrix().invertToRef(invParentMatrix);
  18788. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18789. diffMatrix.decompose(scale, rotation, position);
  18790. if (this.rotationQuaternion) {
  18791. this.rotationQuaternion.copyFrom(rotation);
  18792. }
  18793. else {
  18794. rotation.toEulerAnglesToRef(this.rotation);
  18795. }
  18796. this.position.x = position.x;
  18797. this.position.y = position.y;
  18798. this.position.z = position.z;
  18799. this.scaling.x = scale.x;
  18800. this.scaling.y = scale.y;
  18801. this.scaling.z = scale.z;
  18802. }
  18803. this.parent = node;
  18804. return this;
  18805. };
  18806. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18807. get: function () {
  18808. return this._nonUniformScaling;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18814. if (this._nonUniformScaling === value) {
  18815. return false;
  18816. }
  18817. this._nonUniformScaling = true;
  18818. return true;
  18819. };
  18820. /**
  18821. * Attach the current TransformNode to another TransformNode associated with a bone
  18822. * @param bone Bone affecting the TransformNode
  18823. * @param affectedTransformNode TransformNode associated with the bone
  18824. */
  18825. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18826. this._transformToBoneReferal = affectedTransformNode;
  18827. this.parent = bone;
  18828. if (bone.getWorldMatrix().determinant() < 0) {
  18829. this.scalingDeterminant *= -1;
  18830. }
  18831. return this;
  18832. };
  18833. TransformNode.prototype.detachFromBone = function () {
  18834. if (!this.parent) {
  18835. return this;
  18836. }
  18837. if (this.parent.getWorldMatrix().determinant() < 0) {
  18838. this.scalingDeterminant *= -1;
  18839. }
  18840. this._transformToBoneReferal = null;
  18841. this.parent = null;
  18842. return this;
  18843. };
  18844. /**
  18845. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18846. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18847. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18848. * The passed axis is also normalized.
  18849. * Returns the TransformNode.
  18850. */
  18851. TransformNode.prototype.rotate = function (axis, amount, space) {
  18852. axis.normalize();
  18853. if (!this.rotationQuaternion) {
  18854. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18855. this.rotation = BABYLON.Vector3.Zero();
  18856. }
  18857. var rotationQuaternion;
  18858. if (!space || space === BABYLON.Space.LOCAL) {
  18859. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18860. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18861. }
  18862. else {
  18863. if (this.parent) {
  18864. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18865. invertParentWorldMatrix.invert();
  18866. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18867. }
  18868. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18869. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18870. }
  18871. return this;
  18872. };
  18873. /**
  18874. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18875. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18876. * The passed axis is also normalized.
  18877. * Returns the TransformNode.
  18878. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18879. */
  18880. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18881. axis.normalize();
  18882. if (!this.rotationQuaternion) {
  18883. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18884. this.rotation.copyFromFloats(0, 0, 0);
  18885. }
  18886. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18887. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18888. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18889. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18890. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18891. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18892. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18893. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18894. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18895. return this;
  18896. };
  18897. /**
  18898. * Translates the mesh along the axis vector for the passed distance in the given space.
  18899. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18900. * Returns the TransformNode.
  18901. */
  18902. TransformNode.prototype.translate = function (axis, distance, space) {
  18903. var displacementVector = axis.scale(distance);
  18904. if (!space || space === BABYLON.Space.LOCAL) {
  18905. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18906. this.setPositionWithLocalVector(tempV3);
  18907. }
  18908. else {
  18909. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18910. }
  18911. return this;
  18912. };
  18913. /**
  18914. * Adds a rotation step to the mesh current rotation.
  18915. * x, y, z are Euler angles expressed in radians.
  18916. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18917. * This means this rotation is made in the mesh local space only.
  18918. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18919. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18920. * ```javascript
  18921. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18922. * ```
  18923. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18924. * 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.
  18925. * Returns the TransformNode.
  18926. */
  18927. TransformNode.prototype.addRotation = function (x, y, z) {
  18928. var rotationQuaternion;
  18929. if (this.rotationQuaternion) {
  18930. rotationQuaternion = this.rotationQuaternion;
  18931. }
  18932. else {
  18933. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18934. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18935. }
  18936. var accumulation = BABYLON.Tmp.Quaternion[0];
  18937. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18938. rotationQuaternion.multiplyInPlace(accumulation);
  18939. if (!this.rotationQuaternion) {
  18940. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18941. }
  18942. return this;
  18943. };
  18944. /**
  18945. * Computes the mesh World matrix and returns it.
  18946. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18947. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18948. * If the parameter `force`is set to `true`, the actual computation is done.
  18949. * Returns the mesh World Matrix.
  18950. */
  18951. TransformNode.prototype.computeWorldMatrix = function (force) {
  18952. if (this._isWorldMatrixFrozen) {
  18953. return this._worldMatrix;
  18954. }
  18955. if (!force && this.isSynchronized(true)) {
  18956. this._currentRenderId = this.getScene().getRenderId();
  18957. return this._worldMatrix;
  18958. }
  18959. this._cache.position.copyFrom(this.position);
  18960. this._cache.scaling.copyFrom(this.scaling);
  18961. this._cache.pivotMatrixUpdated = false;
  18962. this._cache.billboardMode = this.billboardMode;
  18963. this._currentRenderId = this.getScene().getRenderId();
  18964. this._childRenderId = this.getScene().getRenderId();
  18965. this._isDirty = false;
  18966. // Scaling
  18967. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18968. // Rotation
  18969. //rotate, if quaternion is set and rotation was used
  18970. if (this.rotationQuaternion) {
  18971. var len = this.rotation.length();
  18972. if (len) {
  18973. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18974. this.rotation.copyFromFloats(0, 0, 0);
  18975. }
  18976. }
  18977. if (this.rotationQuaternion) {
  18978. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18979. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18980. }
  18981. else {
  18982. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18983. this._cache.rotation.copyFrom(this.rotation);
  18984. }
  18985. // Translation
  18986. var camera = this.getScene().activeCamera;
  18987. if (this.infiniteDistance && !this.parent && camera) {
  18988. var cameraWorldMatrix = camera.getWorldMatrix();
  18989. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18990. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18991. }
  18992. else {
  18993. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18994. }
  18995. // Composing transformations
  18996. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18997. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18998. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18999. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19000. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19001. // Need to decompose each rotation here
  19002. var currentPosition = BABYLON.Tmp.Vector3[3];
  19003. if (this.parent && this.parent.getWorldMatrix) {
  19004. if (this._transformToBoneReferal) {
  19005. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19006. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19007. }
  19008. else {
  19009. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19010. }
  19011. }
  19012. else {
  19013. currentPosition.copyFrom(this.position);
  19014. }
  19015. currentPosition.subtractInPlace(camera.globalPosition);
  19016. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19017. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19018. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19019. }
  19020. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19021. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19022. }
  19023. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19024. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19025. }
  19026. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19027. }
  19028. else {
  19029. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19030. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19031. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19032. }
  19033. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19034. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19035. }
  19036. // Local world
  19037. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19038. // Parent
  19039. if (this.parent && this.parent.getWorldMatrix) {
  19040. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19041. if (this._transformToBoneReferal) {
  19042. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19043. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19044. }
  19045. else {
  19046. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19047. }
  19048. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19049. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19050. this._worldMatrix.copyFrom(this._localWorld);
  19051. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19052. }
  19053. else {
  19054. if (this._transformToBoneReferal) {
  19055. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19056. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19057. }
  19058. else {
  19059. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19060. }
  19061. }
  19062. this._markSyncedWithParent();
  19063. }
  19064. else {
  19065. this._worldMatrix.copyFrom(this._localWorld);
  19066. }
  19067. // Post multiply inverse of pivotMatrix
  19068. if (this._postMultiplyPivotMatrix) {
  19069. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19070. }
  19071. // Normal matrix
  19072. if (this.scaling.isNonUniform) {
  19073. this._updateNonUniformScalingState(true);
  19074. }
  19075. else if (this.parent && this.parent._nonUniformScaling) {
  19076. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19077. }
  19078. else {
  19079. this._updateNonUniformScalingState(false);
  19080. }
  19081. this._afterComputeWorldMatrix();
  19082. // Absolute position
  19083. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19084. // Callbacks
  19085. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19086. if (!this._poseMatrix) {
  19087. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19088. }
  19089. // Cache the determinant
  19090. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19091. return this._worldMatrix;
  19092. };
  19093. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19094. };
  19095. /**
  19096. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19097. * @param func: callback function to add
  19098. *
  19099. * Returns the TransformNode.
  19100. */
  19101. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19102. this.onAfterWorldMatrixUpdateObservable.add(func);
  19103. return this;
  19104. };
  19105. /**
  19106. * Removes a registered callback function.
  19107. * Returns the TransformNode.
  19108. */
  19109. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19110. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19111. return this;
  19112. };
  19113. /**
  19114. * Clone the current transform node
  19115. * Returns the new transform node
  19116. * @param name Name of the new clone
  19117. * @param newParent New parent for the clone
  19118. * @param doNotCloneChildren Do not clone children hierarchy
  19119. */
  19120. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19121. var _this = this;
  19122. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19123. result.name = name;
  19124. result.id = name;
  19125. if (newParent) {
  19126. result.parent = newParent;
  19127. }
  19128. if (!doNotCloneChildren) {
  19129. // Children
  19130. var directDescendants = this.getDescendants(true);
  19131. for (var index = 0; index < directDescendants.length; index++) {
  19132. var child = directDescendants[index];
  19133. if (child.clone) {
  19134. child.clone(name + "." + child.name, result);
  19135. }
  19136. }
  19137. }
  19138. return result;
  19139. };
  19140. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19141. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19142. serializationObject.type = this.getClassName();
  19143. // Parent
  19144. if (this.parent) {
  19145. serializationObject.parentId = this.parent.id;
  19146. }
  19147. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19148. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19149. }
  19150. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19151. serializationObject.isEnabled = this.isEnabled();
  19152. // Parent
  19153. if (this.parent) {
  19154. serializationObject.parentId = this.parent.id;
  19155. }
  19156. return serializationObject;
  19157. };
  19158. // Statics
  19159. /**
  19160. * Returns a new TransformNode object parsed from the source provided.
  19161. * The parameter `parsedMesh` is the source.
  19162. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19163. */
  19164. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19165. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19166. if (BABYLON.Tags) {
  19167. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19168. }
  19169. if (parsedTransformNode.localMatrix) {
  19170. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19171. }
  19172. else if (parsedTransformNode.pivotMatrix) {
  19173. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19174. }
  19175. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19176. // Parent
  19177. if (parsedTransformNode.parentId) {
  19178. transformNode._waitingParentId = parsedTransformNode.parentId;
  19179. }
  19180. return transformNode;
  19181. };
  19182. /**
  19183. * Releases resources associated with this transform node.
  19184. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19185. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19186. */
  19187. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19188. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19189. // Animations
  19190. this.getScene().stopAnimation(this);
  19191. // Remove from scene
  19192. this.getScene().removeTransformNode(this);
  19193. this.onAfterWorldMatrixUpdateObservable.clear();
  19194. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19195. };
  19196. // Statics
  19197. TransformNode.BILLBOARDMODE_NONE = 0;
  19198. TransformNode.BILLBOARDMODE_X = 1;
  19199. TransformNode.BILLBOARDMODE_Y = 2;
  19200. TransformNode.BILLBOARDMODE_Z = 4;
  19201. TransformNode.BILLBOARDMODE_ALL = 7;
  19202. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19203. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19204. __decorate([
  19205. BABYLON.serializeAsVector3()
  19206. ], TransformNode.prototype, "_rotation", void 0);
  19207. __decorate([
  19208. BABYLON.serializeAsQuaternion()
  19209. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19210. __decorate([
  19211. BABYLON.serializeAsVector3()
  19212. ], TransformNode.prototype, "_scaling", void 0);
  19213. __decorate([
  19214. BABYLON.serialize()
  19215. ], TransformNode.prototype, "billboardMode", void 0);
  19216. __decorate([
  19217. BABYLON.serialize()
  19218. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], TransformNode.prototype, "infiniteDistance", void 0);
  19222. __decorate([
  19223. BABYLON.serializeAsVector3()
  19224. ], TransformNode.prototype, "position", void 0);
  19225. return TransformNode;
  19226. }(BABYLON.Node));
  19227. BABYLON.TransformNode = TransformNode;
  19228. })(BABYLON || (BABYLON = {}));
  19229. //# sourceMappingURL=babylon.transformNode.js.map
  19230. var BABYLON;
  19231. (function (BABYLON) {
  19232. /**
  19233. * Class used to store all common mesh properties
  19234. */
  19235. var AbstractMesh = /** @class */ (function (_super) {
  19236. __extends(AbstractMesh, _super);
  19237. // Constructor
  19238. /**
  19239. * Creates a new AbstractMesh
  19240. * @param name defines the name of the mesh
  19241. * @param scene defines the hosting scene
  19242. */
  19243. function AbstractMesh(name, scene) {
  19244. if (scene === void 0) { scene = null; }
  19245. var _this = _super.call(this, name, scene, false) || this;
  19246. _this._facetNb = 0; // facet number
  19247. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19248. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19249. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19250. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19251. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19252. _this._subDiv = {
  19253. max: 1,
  19254. X: 1,
  19255. Y: 1,
  19256. Z: 1
  19257. };
  19258. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19259. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19260. // Events
  19261. /**
  19262. * An event triggered when this mesh collides with another one
  19263. */
  19264. _this.onCollideObservable = new BABYLON.Observable();
  19265. /**
  19266. * An event triggered when the collision's position changes
  19267. */
  19268. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19269. /**
  19270. * An event triggered when material is changed
  19271. */
  19272. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19273. // Properties
  19274. /**
  19275. * Gets or sets the orientation for POV movement & rotation
  19276. */
  19277. _this.definedFacingForward = true;
  19278. /**
  19279. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19280. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19281. * * 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.
  19282. * @see http://doc.babylonjs.com/features/occlusionquery
  19283. */
  19284. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19285. /**
  19286. * 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:
  19287. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19288. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19289. * * 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.
  19290. * @see http://doc.babylonjs.com/features/occlusionquery
  19291. */
  19292. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19293. /**
  19294. * 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.
  19295. * The default value is -1 which means don't break the query and wait till the result
  19296. * @see http://doc.babylonjs.com/features/occlusionquery
  19297. */
  19298. _this.occlusionRetryCount = -1;
  19299. _this._occlusionInternalRetryCounter = 0;
  19300. _this._isOccluded = false;
  19301. _this._isOcclusionQueryInProgress = false;
  19302. _this._visibility = 1.0;
  19303. /** Gets or sets the alpha index used to sort transparent meshes
  19304. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19305. */
  19306. _this.alphaIndex = Number.MAX_VALUE;
  19307. /**
  19308. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19309. */
  19310. _this.isVisible = true;
  19311. /**
  19312. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19313. */
  19314. _this.isPickable = true;
  19315. /**
  19316. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19317. */
  19318. _this.showBoundingBox = false;
  19319. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19320. _this.showSubMeshesBoundingBox = false;
  19321. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19322. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19323. */
  19324. _this.isBlocker = false;
  19325. /**
  19326. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19327. */
  19328. _this.enablePointerMoveEvents = false;
  19329. /**
  19330. * Specifies the rendering group id for this mesh (0 by default)
  19331. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19332. */
  19333. _this.renderingGroupId = 0;
  19334. _this._receiveShadows = false;
  19335. /**
  19336. * Gets or sets a boolean indicating if the outline must be rendered as well
  19337. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19338. */
  19339. _this.renderOutline = false;
  19340. /** Defines color to use when rendering outline */
  19341. _this.outlineColor = BABYLON.Color3.Red();
  19342. /** Define width to use when rendering outline */
  19343. _this.outlineWidth = 0.02;
  19344. /**
  19345. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19346. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19347. */
  19348. _this.renderOverlay = false;
  19349. /** Defines color to use when rendering overlay */
  19350. _this.overlayColor = BABYLON.Color3.Red();
  19351. /** Defines alpha to use when rendering overlay */
  19352. _this.overlayAlpha = 0.5;
  19353. _this._hasVertexAlpha = false;
  19354. _this._useVertexColors = true;
  19355. _this._computeBonesUsingShaders = true;
  19356. _this._numBoneInfluencers = 4;
  19357. _this._applyFog = true;
  19358. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19359. _this.useOctreeForRenderingSelection = true;
  19360. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19361. _this.useOctreeForPicking = true;
  19362. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19363. _this.useOctreeForCollisions = true;
  19364. _this._layerMask = 0x0FFFFFFF;
  19365. /**
  19366. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19367. */
  19368. _this.alwaysSelectAsActiveMesh = false;
  19369. /**
  19370. * Gets or sets the current action manager
  19371. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19372. */
  19373. _this.actionManager = null;
  19374. /**
  19375. * Gets or sets impostor used for physic simulation
  19376. * @see http://doc.babylonjs.com/features/physics_engine
  19377. */
  19378. _this.physicsImpostor = null;
  19379. // Collisions
  19380. _this._checkCollisions = false;
  19381. _this._collisionMask = -1;
  19382. _this._collisionGroup = -1;
  19383. /**
  19384. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19385. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19386. */
  19387. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19388. /**
  19389. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19390. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19391. */
  19392. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19393. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19394. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19395. // Edges
  19396. /**
  19397. * Defines edge width used when edgesRenderer is enabled
  19398. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19399. */
  19400. _this.edgesWidth = 1;
  19401. /**
  19402. * Defines edge color used when edgesRenderer is enabled
  19403. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19404. */
  19405. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19406. // Cache
  19407. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19408. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19409. /** @hidden */
  19410. _this._renderId = 0;
  19411. /** @hidden */
  19412. _this._intersectionsInProgress = new Array();
  19413. /** @hidden */
  19414. _this._unIndexed = false;
  19415. /** @hidden */
  19416. _this._lightSources = new Array();
  19417. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19418. if (collidedMesh === void 0) { collidedMesh = null; }
  19419. //TODO move this to the collision coordinator!
  19420. if (_this.getScene().workerCollisions)
  19421. newPosition.multiplyInPlace(_this._collider._radius);
  19422. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19423. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19424. _this.position.addInPlace(_this._diffPositionForCollisions);
  19425. }
  19426. if (collidedMesh) {
  19427. _this.onCollideObservable.notifyObservers(collidedMesh);
  19428. }
  19429. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19430. };
  19431. _this.getScene().addMesh(_this);
  19432. _this._resyncLightSources();
  19433. return _this;
  19434. }
  19435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19436. /**
  19437. * No billboard
  19438. */
  19439. get: function () {
  19440. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19446. /** Billboard on X axis */
  19447. get: function () {
  19448. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19454. /** Billboard on Y axis */
  19455. get: function () {
  19456. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19462. /** Billboard on Z axis */
  19463. get: function () {
  19464. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19470. /** Billboard on all axes */
  19471. get: function () {
  19472. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19478. /**
  19479. * Gets the number of facets in the mesh
  19480. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19481. */
  19482. get: function () {
  19483. return this._facetNb;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19489. /**
  19490. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19491. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19492. */
  19493. get: function () {
  19494. return this._partitioningSubdivisions;
  19495. },
  19496. set: function (nb) {
  19497. this._partitioningSubdivisions = nb;
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19503. /**
  19504. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19505. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19506. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19507. */
  19508. get: function () {
  19509. return this._partitioningBBoxRatio;
  19510. },
  19511. set: function (ratio) {
  19512. this._partitioningBBoxRatio = ratio;
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19518. /**
  19519. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19520. * Works only for updatable meshes.
  19521. * Doesn't work with multi-materials
  19522. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19523. */
  19524. get: function () {
  19525. return this._facetDepthSort;
  19526. },
  19527. set: function (sort) {
  19528. this._facetDepthSort = sort;
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19534. /**
  19535. * The location (Vector3) where the facet depth sort must be computed from.
  19536. * By default, the active camera position.
  19537. * Used only when facet depth sort is enabled
  19538. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19539. */
  19540. get: function () {
  19541. return this._facetDepthSortFrom;
  19542. },
  19543. set: function (location) {
  19544. this._facetDepthSortFrom = location;
  19545. },
  19546. enumerable: true,
  19547. configurable: true
  19548. });
  19549. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19550. /**
  19551. * gets a boolean indicating if facetData is enabled
  19552. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19553. */
  19554. get: function () {
  19555. return this._facetDataEnabled;
  19556. },
  19557. enumerable: true,
  19558. configurable: true
  19559. });
  19560. /** @hidden */
  19561. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19562. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19563. return false;
  19564. }
  19565. this._markSubMeshesAsMiscDirty();
  19566. return true;
  19567. };
  19568. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19569. /** Set a function to call when this mesh collides with another one */
  19570. set: function (callback) {
  19571. if (this._onCollideObserver) {
  19572. this.onCollideObservable.remove(this._onCollideObserver);
  19573. }
  19574. this._onCollideObserver = this.onCollideObservable.add(callback);
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19580. /** Set a function to call when the collision's position changes */
  19581. set: function (callback) {
  19582. if (this._onCollisionPositionChangeObserver) {
  19583. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19584. }
  19585. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19591. /**
  19592. * 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
  19593. * @see http://doc.babylonjs.com/features/occlusionquery
  19594. */
  19595. get: function () {
  19596. return this._isOccluded;
  19597. },
  19598. set: function (value) {
  19599. this._isOccluded = value;
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19605. /**
  19606. * Flag to check the progress status of the query
  19607. * @see http://doc.babylonjs.com/features/occlusionquery
  19608. */
  19609. get: function () {
  19610. return this._isOcclusionQueryInProgress;
  19611. },
  19612. enumerable: true,
  19613. configurable: true
  19614. });
  19615. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19616. /**
  19617. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19618. */
  19619. get: function () {
  19620. return this._visibility;
  19621. },
  19622. /**
  19623. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19624. */
  19625. set: function (value) {
  19626. if (this._visibility === value) {
  19627. return;
  19628. }
  19629. this._visibility = value;
  19630. this._markSubMeshesAsMiscDirty();
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. Object.defineProperty(AbstractMesh.prototype, "material", {
  19636. /** Gets or sets current material */
  19637. get: function () {
  19638. return this._material;
  19639. },
  19640. set: function (value) {
  19641. if (this._material === value) {
  19642. return;
  19643. }
  19644. this._material = value;
  19645. if (this.onMaterialChangedObservable.hasObservers) {
  19646. this.onMaterialChangedObservable.notifyObservers(this);
  19647. }
  19648. if (!this.subMeshes) {
  19649. return;
  19650. }
  19651. this._unBindEffect();
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19657. /**
  19658. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19659. * @see http://doc.babylonjs.com/babylon101/shadows
  19660. */
  19661. get: function () {
  19662. return this._receiveShadows;
  19663. },
  19664. set: function (value) {
  19665. if (this._receiveShadows === value) {
  19666. return;
  19667. }
  19668. this._receiveShadows = value;
  19669. this._markSubMeshesAsLightDirty();
  19670. },
  19671. enumerable: true,
  19672. configurable: true
  19673. });
  19674. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19675. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19676. get: function () {
  19677. return this._hasVertexAlpha;
  19678. },
  19679. set: function (value) {
  19680. if (this._hasVertexAlpha === value) {
  19681. return;
  19682. }
  19683. this._hasVertexAlpha = value;
  19684. this._markSubMeshesAsAttributesDirty();
  19685. this._markSubMeshesAsMiscDirty();
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19691. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19692. get: function () {
  19693. return this._useVertexColors;
  19694. },
  19695. set: function (value) {
  19696. if (this._useVertexColors === value) {
  19697. return;
  19698. }
  19699. this._useVertexColors = value;
  19700. this._markSubMeshesAsAttributesDirty();
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19706. /**
  19707. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19708. */
  19709. get: function () {
  19710. return this._computeBonesUsingShaders;
  19711. },
  19712. set: function (value) {
  19713. if (this._computeBonesUsingShaders === value) {
  19714. return;
  19715. }
  19716. this._computeBonesUsingShaders = value;
  19717. this._markSubMeshesAsAttributesDirty();
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19723. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19724. get: function () {
  19725. return this._numBoneInfluencers;
  19726. },
  19727. set: function (value) {
  19728. if (this._numBoneInfluencers === value) {
  19729. return;
  19730. }
  19731. this._numBoneInfluencers = value;
  19732. this._markSubMeshesAsAttributesDirty();
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19738. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19739. get: function () {
  19740. return this._applyFog;
  19741. },
  19742. set: function (value) {
  19743. if (this._applyFog === value) {
  19744. return;
  19745. }
  19746. this._applyFog = value;
  19747. this._markSubMeshesAsMiscDirty();
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19753. /**
  19754. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19755. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19756. */
  19757. get: function () {
  19758. return this._layerMask;
  19759. },
  19760. set: function (value) {
  19761. if (value === this._layerMask) {
  19762. return;
  19763. }
  19764. this._layerMask = value;
  19765. this._resyncLightSources();
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19771. /**
  19772. * Gets or sets a collision mask used to mask collisions (default is -1).
  19773. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19774. */
  19775. get: function () {
  19776. return this._collisionMask;
  19777. },
  19778. set: function (mask) {
  19779. this._collisionMask = !isNaN(mask) ? mask : -1;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19785. /**
  19786. * Gets or sets the current collision group mask (-1 by default).
  19787. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19788. */
  19789. get: function () {
  19790. return this._collisionGroup;
  19791. },
  19792. set: function (mask) {
  19793. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19799. /** @hidden */
  19800. get: function () {
  19801. return null;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19807. get: function () {
  19808. return this._skeleton;
  19809. },
  19810. /**
  19811. * Gets or sets a skeleton to apply skining transformations
  19812. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19813. */
  19814. set: function (value) {
  19815. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19816. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19817. }
  19818. if (value && value.needInitialSkinMatrix) {
  19819. value._registerMeshWithPoseMatrix(this);
  19820. }
  19821. this._skeleton = value;
  19822. if (!this._skeleton) {
  19823. this._bonesTransformMatrices = null;
  19824. }
  19825. this._markSubMeshesAsAttributesDirty();
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. /**
  19831. * Returns the string "AbstractMesh"
  19832. * @returns "AbstractMesh"
  19833. */
  19834. AbstractMesh.prototype.getClassName = function () {
  19835. return "AbstractMesh";
  19836. };
  19837. /**
  19838. * Gets a string representation of the current mesh
  19839. * @param fullDetails defines a boolean indicating if full details must be included
  19840. * @returns a string representation of the current mesh
  19841. */
  19842. AbstractMesh.prototype.toString = function (fullDetails) {
  19843. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19844. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19845. if (this._skeleton) {
  19846. ret += ", skeleton: " + this._skeleton.name;
  19847. }
  19848. if (fullDetails) {
  19849. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19850. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19851. }
  19852. return ret;
  19853. };
  19854. /** @hidden */
  19855. AbstractMesh.prototype._rebuild = function () {
  19856. if (this._occlusionQuery) {
  19857. this._occlusionQuery = null;
  19858. }
  19859. if (this._edgesRenderer) {
  19860. this._edgesRenderer._rebuild();
  19861. }
  19862. if (!this.subMeshes) {
  19863. return;
  19864. }
  19865. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19866. var subMesh = _a[_i];
  19867. subMesh._rebuild();
  19868. }
  19869. };
  19870. /** @hidden */
  19871. AbstractMesh.prototype._resyncLightSources = function () {
  19872. this._lightSources.length = 0;
  19873. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19874. var light = _a[_i];
  19875. if (!light.isEnabled()) {
  19876. continue;
  19877. }
  19878. if (light.canAffectMesh(this)) {
  19879. this._lightSources.push(light);
  19880. }
  19881. }
  19882. this._markSubMeshesAsLightDirty();
  19883. };
  19884. /** @hidden */
  19885. AbstractMesh.prototype._resyncLighSource = function (light) {
  19886. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19887. var index = this._lightSources.indexOf(light);
  19888. if (index === -1) {
  19889. if (!isIn) {
  19890. return;
  19891. }
  19892. this._lightSources.push(light);
  19893. }
  19894. else {
  19895. if (isIn) {
  19896. return;
  19897. }
  19898. this._lightSources.splice(index, 1);
  19899. }
  19900. this._markSubMeshesAsLightDirty();
  19901. };
  19902. /** @hidden */
  19903. AbstractMesh.prototype._unBindEffect = function () {
  19904. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19905. var subMesh = _a[_i];
  19906. subMesh.setEffect(null);
  19907. }
  19908. };
  19909. /** @hidden */
  19910. AbstractMesh.prototype._removeLightSource = function (light) {
  19911. var index = this._lightSources.indexOf(light);
  19912. if (index === -1) {
  19913. return;
  19914. }
  19915. this._lightSources.splice(index, 1);
  19916. this._markSubMeshesAsLightDirty();
  19917. };
  19918. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19919. if (!this.subMeshes) {
  19920. return;
  19921. }
  19922. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19923. var subMesh = _a[_i];
  19924. if (subMesh._materialDefines) {
  19925. func(subMesh._materialDefines);
  19926. }
  19927. }
  19928. };
  19929. /** @hidden */
  19930. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19931. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19932. };
  19933. /** @hidden */
  19934. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19935. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19936. };
  19937. /** @hidden */
  19938. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19939. if (!this.subMeshes) {
  19940. return;
  19941. }
  19942. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19943. var subMesh = _a[_i];
  19944. var material = subMesh.getMaterial();
  19945. if (material) {
  19946. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19947. }
  19948. }
  19949. };
  19950. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19951. /**
  19952. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19953. */
  19954. get: function () {
  19955. return this._scaling;
  19956. },
  19957. set: function (newScaling) {
  19958. this._scaling = newScaling;
  19959. if (this.physicsImpostor) {
  19960. this.physicsImpostor.forceUpdate();
  19961. }
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. // Methods
  19967. /**
  19968. * Disables the mesh edge rendering mode
  19969. * @returns the currentAbstractMesh
  19970. */
  19971. AbstractMesh.prototype.disableEdgesRendering = function () {
  19972. if (this._edgesRenderer) {
  19973. this._edgesRenderer.dispose();
  19974. this._edgesRenderer = null;
  19975. }
  19976. return this;
  19977. };
  19978. /**
  19979. * Enables the edge rendering mode on the mesh.
  19980. * This mode makes the mesh edges visible
  19981. * @param epsilon defines the maximal distance between two angles to detect a face
  19982. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19983. * @returns the currentAbstractMesh
  19984. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19985. */
  19986. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19987. if (epsilon === void 0) { epsilon = 0.95; }
  19988. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19989. this.disableEdgesRendering();
  19990. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19991. return this;
  19992. };
  19993. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19994. /**
  19995. * Returns true if the mesh is blocked. Implemented by child classes
  19996. */
  19997. get: function () {
  19998. return false;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. /**
  20004. * Returns the mesh itself by default. Implemented by child classes
  20005. * @param camera defines the camera to use to pick the right LOD level
  20006. * @returns the currentAbstractMesh
  20007. */
  20008. AbstractMesh.prototype.getLOD = function (camera) {
  20009. return this;
  20010. };
  20011. /**
  20012. * Returns 0 by default. Implemented by child classes
  20013. * @returns an integer
  20014. */
  20015. AbstractMesh.prototype.getTotalVertices = function () {
  20016. return 0;
  20017. };
  20018. /**
  20019. * Returns null by default. Implemented by child classes
  20020. * @returns null
  20021. */
  20022. AbstractMesh.prototype.getIndices = function () {
  20023. return null;
  20024. };
  20025. /**
  20026. * Returns the array of the requested vertex data kind. Implemented by child classes
  20027. * @param kind defines the vertex data kind to use
  20028. * @returns null
  20029. */
  20030. AbstractMesh.prototype.getVerticesData = function (kind) {
  20031. return null;
  20032. };
  20033. /**
  20034. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20035. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20036. * Note that a new underlying VertexBuffer object is created each call.
  20037. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20038. * @param kind defines vertex data kind:
  20039. * * BABYLON.VertexBuffer.PositionKind
  20040. * * BABYLON.VertexBuffer.UVKind
  20041. * * BABYLON.VertexBuffer.UV2Kind
  20042. * * BABYLON.VertexBuffer.UV3Kind
  20043. * * BABYLON.VertexBuffer.UV4Kind
  20044. * * BABYLON.VertexBuffer.UV5Kind
  20045. * * BABYLON.VertexBuffer.UV6Kind
  20046. * * BABYLON.VertexBuffer.ColorKind
  20047. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20048. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20049. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20050. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20051. * @param data defines the data source
  20052. * @param updatable defines if the data must be flagged as updatable (or static)
  20053. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20054. * @returns the current mesh
  20055. */
  20056. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20057. return this;
  20058. };
  20059. /**
  20060. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20061. * If the mesh has no geometry, it is simply returned as it is.
  20062. * @param kind defines vertex data kind:
  20063. * * BABYLON.VertexBuffer.PositionKind
  20064. * * BABYLON.VertexBuffer.UVKind
  20065. * * BABYLON.VertexBuffer.UV2Kind
  20066. * * BABYLON.VertexBuffer.UV3Kind
  20067. * * BABYLON.VertexBuffer.UV4Kind
  20068. * * BABYLON.VertexBuffer.UV5Kind
  20069. * * BABYLON.VertexBuffer.UV6Kind
  20070. * * BABYLON.VertexBuffer.ColorKind
  20071. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20072. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20073. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20074. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20075. * @param data defines the data source
  20076. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20077. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20078. * @returns the current mesh
  20079. */
  20080. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20081. return this;
  20082. };
  20083. /**
  20084. * Sets the mesh indices,
  20085. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20086. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20087. * @param totalVertices Defines the total number of vertices
  20088. * @returns the current mesh
  20089. */
  20090. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20091. return this;
  20092. };
  20093. /**
  20094. * Gets a boolean indicating if specific vertex data is present
  20095. * @param kind defines the vertex data kind to use
  20096. * @returns true is data kind is present
  20097. */
  20098. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20099. return false;
  20100. };
  20101. /**
  20102. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20103. * @returns a BoundingInfo
  20104. */
  20105. AbstractMesh.prototype.getBoundingInfo = function () {
  20106. if (this._masterMesh) {
  20107. return this._masterMesh.getBoundingInfo();
  20108. }
  20109. if (!this._boundingInfo) {
  20110. // this._boundingInfo is being created here
  20111. this._updateBoundingInfo();
  20112. }
  20113. // cannot be null.
  20114. return this._boundingInfo;
  20115. };
  20116. /**
  20117. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20118. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20119. * @returns the current mesh
  20120. */
  20121. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20122. if (includeDescendants === void 0) { includeDescendants = true; }
  20123. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20124. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20125. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20126. if (maxDimension === 0) {
  20127. return this;
  20128. }
  20129. var scale = 1 / maxDimension;
  20130. this.scaling.scaleInPlace(scale);
  20131. return this;
  20132. };
  20133. /**
  20134. * Overwrite the current bounding info
  20135. * @param boundingInfo defines the new bounding info
  20136. * @returns the current mesh
  20137. */
  20138. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20139. this._boundingInfo = boundingInfo;
  20140. return this;
  20141. };
  20142. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20143. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20144. get: function () {
  20145. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. /** @hidden */
  20151. AbstractMesh.prototype._preActivate = function () {
  20152. };
  20153. /** @hidden */
  20154. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20155. };
  20156. /** @hidden */
  20157. AbstractMesh.prototype._activate = function (renderId) {
  20158. this._renderId = renderId;
  20159. };
  20160. /**
  20161. * Gets the current world matrix
  20162. * @returns a Matrix
  20163. */
  20164. AbstractMesh.prototype.getWorldMatrix = function () {
  20165. if (this._masterMesh) {
  20166. return this._masterMesh.getWorldMatrix();
  20167. }
  20168. return _super.prototype.getWorldMatrix.call(this);
  20169. };
  20170. /** @hidden */
  20171. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20172. if (this._masterMesh) {
  20173. return this._masterMesh._getWorldMatrixDeterminant();
  20174. }
  20175. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20176. };
  20177. // ================================== Point of View Movement =================================
  20178. /**
  20179. * Perform relative position change from the point of view of behind the front of the mesh.
  20180. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20181. * Supports definition of mesh facing forward or backward
  20182. * @param amountRight defines the distance on the right axis
  20183. * @param amountUp defines the distance on the up axis
  20184. * @param amountForward defines the distance on the forward axis
  20185. * @returns the current mesh
  20186. */
  20187. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20188. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20189. return this;
  20190. };
  20191. /**
  20192. * Calculate relative position change from the point of view of behind the front of the mesh.
  20193. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20194. * Supports definition of mesh facing forward or backward
  20195. * @param amountRight defines the distance on the right axis
  20196. * @param amountUp defines the distance on the up axis
  20197. * @param amountForward defines the distance on the forward axis
  20198. * @returns the new displacement vector
  20199. */
  20200. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20201. var rotMatrix = new BABYLON.Matrix();
  20202. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20203. rotQuaternion.toRotationMatrix(rotMatrix);
  20204. var translationDelta = BABYLON.Vector3.Zero();
  20205. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20206. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20207. return translationDelta;
  20208. };
  20209. // ================================== Point of View Rotation =================================
  20210. /**
  20211. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20212. * Supports definition of mesh facing forward or backward
  20213. * @param flipBack defines the flip
  20214. * @param twirlClockwise defines the twirl
  20215. * @param tiltRight defines the tilt
  20216. * @returns the current mesh
  20217. */
  20218. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20219. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20220. return this;
  20221. };
  20222. /**
  20223. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20224. * Supports definition of mesh facing forward or backward.
  20225. * @param flipBack defines the flip
  20226. * @param twirlClockwise defines the twirl
  20227. * @param tiltRight defines the tilt
  20228. * @returns the new rotation vector
  20229. */
  20230. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20231. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20232. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20233. };
  20234. /**
  20235. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20236. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20237. * @returns the new bounding vectors
  20238. */
  20239. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20240. if (includeDescendants === void 0) { includeDescendants = true; }
  20241. // Ensures that all world matrix will be recomputed.
  20242. this.getScene().incrementRenderId();
  20243. this.computeWorldMatrix(true);
  20244. var min;
  20245. var max;
  20246. var boundingInfo = this.getBoundingInfo();
  20247. if (!this.subMeshes) {
  20248. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20249. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20250. }
  20251. else {
  20252. min = boundingInfo.boundingBox.minimumWorld;
  20253. max = boundingInfo.boundingBox.maximumWorld;
  20254. }
  20255. if (includeDescendants) {
  20256. var descendants = this.getDescendants(false);
  20257. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20258. var descendant = descendants_1[_i];
  20259. var childMesh = descendant;
  20260. childMesh.computeWorldMatrix(true);
  20261. //make sure we have the needed params to get mix and max
  20262. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20263. continue;
  20264. }
  20265. var childBoundingInfo = childMesh.getBoundingInfo();
  20266. var boundingBox = childBoundingInfo.boundingBox;
  20267. var minBox = boundingBox.minimumWorld;
  20268. var maxBox = boundingBox.maximumWorld;
  20269. BABYLON.Tools.CheckExtends(minBox, min, max);
  20270. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20271. }
  20272. }
  20273. return {
  20274. min: min,
  20275. max: max
  20276. };
  20277. };
  20278. /** @hidden */
  20279. AbstractMesh.prototype._updateBoundingInfo = function () {
  20280. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20281. this._boundingInfo.update(this.worldMatrixFromCache);
  20282. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20283. return this;
  20284. };
  20285. /** @hidden */
  20286. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20287. if (!this.subMeshes) {
  20288. return this;
  20289. }
  20290. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20291. var subMesh = this.subMeshes[subIndex];
  20292. if (!subMesh.IsGlobal) {
  20293. subMesh.updateBoundingInfo(matrix);
  20294. }
  20295. }
  20296. return this;
  20297. };
  20298. /** @hidden */
  20299. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20300. // Bounding info
  20301. this._updateBoundingInfo();
  20302. };
  20303. /**
  20304. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20305. * A mesh is in the frustum if its bounding box intersects the frustum
  20306. * @param frustumPlanes defines the frustum to test
  20307. * @returns true if the mesh is in the frustum planes
  20308. */
  20309. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20310. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20311. };
  20312. /**
  20313. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20314. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20315. * @param frustumPlanes defines the frustum to test
  20316. * @returns true if the mesh is completely in the frustum planes
  20317. */
  20318. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20319. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20320. };
  20321. /**
  20322. * True if the mesh intersects another mesh or a SolidParticle object
  20323. * @param mesh defines a target mesh or SolidParticle to test
  20324. * @param precise 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)
  20325. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20326. * @returns true if there is an intersection
  20327. */
  20328. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20329. if (precise === void 0) { precise = false; }
  20330. if (!this._boundingInfo || !mesh._boundingInfo) {
  20331. return false;
  20332. }
  20333. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20334. return true;
  20335. }
  20336. if (includeDescendants) {
  20337. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20338. var child = _a[_i];
  20339. if (child.intersectsMesh(mesh, precise, true)) {
  20340. return true;
  20341. }
  20342. }
  20343. }
  20344. return false;
  20345. };
  20346. /**
  20347. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20348. * @param point defines the point to test
  20349. * @returns true if there is an intersection
  20350. */
  20351. AbstractMesh.prototype.intersectsPoint = function (point) {
  20352. if (!this._boundingInfo) {
  20353. return false;
  20354. }
  20355. return this._boundingInfo.intersectsPoint(point);
  20356. };
  20357. /**
  20358. * Gets the current physics impostor
  20359. * @see http://doc.babylonjs.com/features/physics_engine
  20360. * @returns a physics impostor or null
  20361. */
  20362. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20363. return this.physicsImpostor;
  20364. };
  20365. /**
  20366. * Gets the position of the current mesh in camera space
  20367. * @param camera defines the camera to use
  20368. * @returns a position
  20369. */
  20370. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20371. if (camera === void 0) { camera = null; }
  20372. if (!camera) {
  20373. camera = this.getScene().activeCamera;
  20374. }
  20375. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20376. };
  20377. /**
  20378. * Returns the distance from the mesh to the active camera
  20379. * @param camera defines the camera to use
  20380. * @returns the distance
  20381. */
  20382. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20383. if (camera === void 0) { camera = null; }
  20384. if (!camera) {
  20385. camera = this.getScene().activeCamera;
  20386. }
  20387. return this.absolutePosition.subtract(camera.position).length();
  20388. };
  20389. /**
  20390. * Apply a physic impulse to the mesh
  20391. * @param force defines the force to apply
  20392. * @param contactPoint defines where to apply the force
  20393. * @returns the current mesh
  20394. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20395. */
  20396. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20397. if (!this.physicsImpostor) {
  20398. return this;
  20399. }
  20400. this.physicsImpostor.applyImpulse(force, contactPoint);
  20401. return this;
  20402. };
  20403. /**
  20404. * Creates a physic joint between two meshes
  20405. * @param otherMesh defines the other mesh to use
  20406. * @param pivot1 defines the pivot to use on this mesh
  20407. * @param pivot2 defines the pivot to use on the other mesh
  20408. * @param options defines additional options (can be plugin dependent)
  20409. * @returns the current mesh
  20410. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20411. */
  20412. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20413. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20414. return this;
  20415. }
  20416. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20417. mainPivot: pivot1,
  20418. connectedPivot: pivot2,
  20419. nativeParams: options
  20420. });
  20421. return this;
  20422. };
  20423. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20424. // Collisions
  20425. /**
  20426. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20427. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20428. */
  20429. get: function () {
  20430. return this._checkCollisions;
  20431. },
  20432. set: function (collisionEnabled) {
  20433. this._checkCollisions = collisionEnabled;
  20434. if (this.getScene().workerCollisions) {
  20435. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20436. }
  20437. },
  20438. enumerable: true,
  20439. configurable: true
  20440. });
  20441. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20442. /**
  20443. * Gets Collider object used to compute collisions (not physics)
  20444. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20445. */
  20446. get: function () {
  20447. return this._collider;
  20448. },
  20449. enumerable: true,
  20450. configurable: true
  20451. });
  20452. /**
  20453. * Move the mesh using collision engine
  20454. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20455. * @param displacement defines the requested displacement vector
  20456. * @returns the current mesh
  20457. */
  20458. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20459. var globalPosition = this.getAbsolutePosition();
  20460. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20461. if (!this._collider) {
  20462. this._collider = new BABYLON.Collider();
  20463. }
  20464. this._collider._radius = this.ellipsoid;
  20465. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20466. return this;
  20467. };
  20468. // Submeshes octree
  20469. /**
  20470. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20471. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20472. * @param maxCapacity defines the maximum size of each block (64 by default)
  20473. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20474. * @returns the new octree
  20475. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20476. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20477. */
  20478. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20479. if (maxCapacity === void 0) { maxCapacity = 64; }
  20480. if (maxDepth === void 0) { maxDepth = 2; }
  20481. if (!this._submeshesOctree) {
  20482. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20483. }
  20484. this.computeWorldMatrix(true);
  20485. var boundingInfo = this.getBoundingInfo();
  20486. // Update octree
  20487. var bbox = boundingInfo.boundingBox;
  20488. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20489. return this._submeshesOctree;
  20490. };
  20491. // Collisions
  20492. /** @hidden */
  20493. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20494. this._generatePointsArray();
  20495. if (!this._positions) {
  20496. return this;
  20497. }
  20498. // Transformation
  20499. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20500. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20501. subMesh._lastColliderWorldVertices = [];
  20502. subMesh._trianglePlanes = [];
  20503. var start = subMesh.verticesStart;
  20504. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20505. for (var i = start; i < end; i++) {
  20506. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20507. }
  20508. }
  20509. // Collide
  20510. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20511. if (collider.collisionFound) {
  20512. collider.collidedMesh = this;
  20513. }
  20514. return this;
  20515. };
  20516. /** @hidden */
  20517. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20518. var subMeshes;
  20519. var len;
  20520. // Octrees
  20521. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20522. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20523. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20524. len = intersections.length;
  20525. subMeshes = intersections.data;
  20526. }
  20527. else {
  20528. subMeshes = this.subMeshes;
  20529. len = subMeshes.length;
  20530. }
  20531. for (var index = 0; index < len; index++) {
  20532. var subMesh = subMeshes[index];
  20533. // Bounding test
  20534. if (len > 1 && !subMesh._checkCollision(collider))
  20535. continue;
  20536. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20537. }
  20538. return this;
  20539. };
  20540. /** @hidden */
  20541. AbstractMesh.prototype._checkCollision = function (collider) {
  20542. // Bounding box test
  20543. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20544. return this;
  20545. // Transformation matrix
  20546. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20547. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20548. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20549. return this;
  20550. };
  20551. // Picking
  20552. /** @hidden */
  20553. AbstractMesh.prototype._generatePointsArray = function () {
  20554. return false;
  20555. };
  20556. /**
  20557. * Checks if the passed Ray intersects with the mesh
  20558. * @param ray defines the ray to use
  20559. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20560. * @returns the picking info
  20561. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20562. */
  20563. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20564. var pickingInfo = new BABYLON.PickingInfo();
  20565. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20566. return pickingInfo;
  20567. }
  20568. if (!this._generatePointsArray()) {
  20569. return pickingInfo;
  20570. }
  20571. var intersectInfo = null;
  20572. // Octrees
  20573. var subMeshes;
  20574. var len;
  20575. if (this._submeshesOctree && this.useOctreeForPicking) {
  20576. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20577. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20578. len = intersections.length;
  20579. subMeshes = intersections.data;
  20580. }
  20581. else {
  20582. subMeshes = this.subMeshes;
  20583. len = subMeshes.length;
  20584. }
  20585. for (var index = 0; index < len; index++) {
  20586. var subMesh = subMeshes[index];
  20587. // Bounding test
  20588. if (len > 1 && !subMesh.canIntersects(ray))
  20589. continue;
  20590. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20591. if (currentIntersectInfo) {
  20592. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20593. intersectInfo = currentIntersectInfo;
  20594. intersectInfo.subMeshId = index;
  20595. if (fastCheck) {
  20596. break;
  20597. }
  20598. }
  20599. }
  20600. }
  20601. if (intersectInfo) {
  20602. // Get picked point
  20603. var world = this.getWorldMatrix();
  20604. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20605. var direction = ray.direction.clone();
  20606. direction = direction.scale(intersectInfo.distance);
  20607. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20608. var pickedPoint = worldOrigin.add(worldDirection);
  20609. // Return result
  20610. pickingInfo.hit = true;
  20611. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20612. pickingInfo.pickedPoint = pickedPoint;
  20613. pickingInfo.pickedMesh = this;
  20614. pickingInfo.bu = intersectInfo.bu || 0;
  20615. pickingInfo.bv = intersectInfo.bv || 0;
  20616. pickingInfo.faceId = intersectInfo.faceId;
  20617. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20618. return pickingInfo;
  20619. }
  20620. return pickingInfo;
  20621. };
  20622. /**
  20623. * Clones the current mesh
  20624. * @param name defines the mesh name
  20625. * @param newParent defines the new mesh parent
  20626. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20627. * @returns the new mesh
  20628. */
  20629. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20630. return null;
  20631. };
  20632. /**
  20633. * Disposes all the submeshes of the current meshnp
  20634. * @returns the current mesh
  20635. */
  20636. AbstractMesh.prototype.releaseSubMeshes = function () {
  20637. if (this.subMeshes) {
  20638. while (this.subMeshes.length) {
  20639. this.subMeshes[0].dispose();
  20640. }
  20641. }
  20642. else {
  20643. this.subMeshes = new Array();
  20644. }
  20645. return this;
  20646. };
  20647. /**
  20648. * Releases resources associated with this abstract mesh.
  20649. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20650. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20651. */
  20652. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20653. var _this = this;
  20654. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20655. var index;
  20656. // Smart Array Retainers.
  20657. this.getScene().freeActiveMeshes();
  20658. this.getScene().freeRenderingGroups();
  20659. // Action manager
  20660. if (this.actionManager !== undefined && this.actionManager !== null) {
  20661. this.actionManager.dispose();
  20662. this.actionManager = null;
  20663. }
  20664. // Skeleton
  20665. this._skeleton = null;
  20666. // Physics
  20667. if (this.physicsImpostor) {
  20668. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20669. }
  20670. // Intersections in progress
  20671. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20672. var other = this._intersectionsInProgress[index];
  20673. var pos = other._intersectionsInProgress.indexOf(this);
  20674. other._intersectionsInProgress.splice(pos, 1);
  20675. }
  20676. this._intersectionsInProgress = [];
  20677. // Lights
  20678. var lights = this.getScene().lights;
  20679. lights.forEach(function (light) {
  20680. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20681. if (meshIndex !== -1) {
  20682. light.includedOnlyMeshes.splice(meshIndex, 1);
  20683. }
  20684. meshIndex = light.excludedMeshes.indexOf(_this);
  20685. if (meshIndex !== -1) {
  20686. light.excludedMeshes.splice(meshIndex, 1);
  20687. }
  20688. // Shadow generators
  20689. var generator = light.getShadowGenerator();
  20690. if (generator) {
  20691. var shadowMap = generator.getShadowMap();
  20692. if (shadowMap && shadowMap.renderList) {
  20693. meshIndex = shadowMap.renderList.indexOf(_this);
  20694. if (meshIndex !== -1) {
  20695. shadowMap.renderList.splice(meshIndex, 1);
  20696. }
  20697. }
  20698. }
  20699. });
  20700. // Edges
  20701. if (this._edgesRenderer) {
  20702. this._edgesRenderer.dispose();
  20703. this._edgesRenderer = null;
  20704. }
  20705. // SubMeshes
  20706. if (this.getClassName() !== "InstancedMesh") {
  20707. this.releaseSubMeshes();
  20708. }
  20709. // Octree
  20710. var sceneOctree = this.getScene().selectionOctree;
  20711. if (sceneOctree !== undefined && sceneOctree !== null) {
  20712. var index = sceneOctree.dynamicContent.indexOf(this);
  20713. if (index !== -1) {
  20714. sceneOctree.dynamicContent.splice(index, 1);
  20715. }
  20716. }
  20717. // Query
  20718. var engine = this.getScene().getEngine();
  20719. if (this._occlusionQuery) {
  20720. this._isOcclusionQueryInProgress = false;
  20721. engine.deleteQuery(this._occlusionQuery);
  20722. this._occlusionQuery = null;
  20723. }
  20724. // Engine
  20725. engine.wipeCaches();
  20726. // Remove from scene
  20727. this.getScene().removeMesh(this);
  20728. if (disposeMaterialAndTextures) {
  20729. if (this.material) {
  20730. this.material.dispose(false, true);
  20731. }
  20732. }
  20733. if (!doNotRecurse) {
  20734. // Particles
  20735. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20736. if (this.getScene().particleSystems[index].emitter === this) {
  20737. this.getScene().particleSystems[index].dispose();
  20738. index--;
  20739. }
  20740. }
  20741. }
  20742. // facet data
  20743. if (this._facetDataEnabled) {
  20744. this.disableFacetData();
  20745. }
  20746. this.onAfterWorldMatrixUpdateObservable.clear();
  20747. this.onCollideObservable.clear();
  20748. this.onCollisionPositionChangeObservable.clear();
  20749. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20750. };
  20751. /**
  20752. * Adds the passed mesh as a child to the current mesh
  20753. * @param mesh defines the child mesh
  20754. * @returns the current mesh
  20755. */
  20756. AbstractMesh.prototype.addChild = function (mesh) {
  20757. mesh.setParent(this);
  20758. return this;
  20759. };
  20760. /**
  20761. * Removes the passed mesh from the current mesh children list
  20762. * @param mesh defines the child mesh
  20763. * @returns the current mesh
  20764. */
  20765. AbstractMesh.prototype.removeChild = function (mesh) {
  20766. mesh.setParent(null);
  20767. return this;
  20768. };
  20769. // Facet data
  20770. /** @hidden */
  20771. AbstractMesh.prototype._initFacetData = function () {
  20772. if (!this._facetNormals) {
  20773. this._facetNormals = new Array();
  20774. }
  20775. if (!this._facetPositions) {
  20776. this._facetPositions = new Array();
  20777. }
  20778. if (!this._facetPartitioning) {
  20779. this._facetPartitioning = new Array();
  20780. }
  20781. this._facetNb = (this.getIndices().length / 3) | 0;
  20782. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20783. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20784. for (var f = 0; f < this._facetNb; f++) {
  20785. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20786. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20787. }
  20788. this._facetDataEnabled = true;
  20789. return this;
  20790. };
  20791. /**
  20792. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20793. * This method can be called within the render loop.
  20794. * 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
  20795. * @returns the current mesh
  20796. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20797. */
  20798. AbstractMesh.prototype.updateFacetData = function () {
  20799. if (!this._facetDataEnabled) {
  20800. this._initFacetData();
  20801. }
  20802. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20803. var indices = this.getIndices();
  20804. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20805. var bInfo = this.getBoundingInfo();
  20806. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20807. // init arrays, matrix and sort function on first call
  20808. this._facetDepthSortEnabled = true;
  20809. if (indices instanceof Uint16Array) {
  20810. this._depthSortedIndices = new Uint16Array(indices);
  20811. }
  20812. else if (indices instanceof Uint32Array) {
  20813. this._depthSortedIndices = new Uint32Array(indices);
  20814. }
  20815. else {
  20816. var needs32bits = false;
  20817. for (var i = 0; i < indices.length; i++) {
  20818. if (indices[i] > 65535) {
  20819. needs32bits = true;
  20820. break;
  20821. }
  20822. }
  20823. if (needs32bits) {
  20824. this._depthSortedIndices = new Uint32Array(indices);
  20825. }
  20826. else {
  20827. this._depthSortedIndices = new Uint16Array(indices);
  20828. }
  20829. }
  20830. this._facetDepthSortFunction = function (f1, f2) {
  20831. return (f2.sqDistance - f1.sqDistance);
  20832. };
  20833. if (!this._facetDepthSortFrom) {
  20834. var camera = this.getScene().activeCamera;
  20835. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20836. }
  20837. this._depthSortedFacets = [];
  20838. for (var f = 0; f < this._facetNb; f++) {
  20839. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20840. this._depthSortedFacets.push(depthSortedFacet);
  20841. }
  20842. this._invertedMatrix = BABYLON.Matrix.Identity();
  20843. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20844. }
  20845. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20846. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20847. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20848. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20849. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20850. this._subDiv.max = this._partitioningSubdivisions;
  20851. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20852. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20853. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20854. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20855. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20856. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20857. // set the parameters for ComputeNormals()
  20858. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20859. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20860. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20861. this._facetParameters.bInfo = bInfo;
  20862. this._facetParameters.bbSize = this._bbSize;
  20863. this._facetParameters.subDiv = this._subDiv;
  20864. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20865. this._facetParameters.depthSort = this._facetDepthSort;
  20866. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20867. this.computeWorldMatrix(true);
  20868. this._worldMatrix.invertToRef(this._invertedMatrix);
  20869. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20870. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20871. }
  20872. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20873. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20874. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20875. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20876. var l = (this._depthSortedIndices.length / 3) | 0;
  20877. for (var f = 0; f < l; f++) {
  20878. var sind = this._depthSortedFacets[f].ind;
  20879. this._depthSortedIndices[f * 3] = indices[sind];
  20880. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20881. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20882. }
  20883. this.updateIndices(this._depthSortedIndices);
  20884. }
  20885. return this;
  20886. };
  20887. /**
  20888. * Returns the facetLocalNormals array.
  20889. * The normals are expressed in the mesh local spac
  20890. * @returns an array of Vector3
  20891. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20892. */
  20893. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20894. if (!this._facetNormals) {
  20895. this.updateFacetData();
  20896. }
  20897. return this._facetNormals;
  20898. };
  20899. /**
  20900. * Returns the facetLocalPositions array.
  20901. * The facet positions are expressed in the mesh local space
  20902. * @returns an array of Vector3
  20903. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20904. */
  20905. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20906. if (!this._facetPositions) {
  20907. this.updateFacetData();
  20908. }
  20909. return this._facetPositions;
  20910. };
  20911. /**
  20912. * Returns the facetLocalPartioning array
  20913. * @returns an array of array of numbers
  20914. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20915. */
  20916. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20917. if (!this._facetPartitioning) {
  20918. this.updateFacetData();
  20919. }
  20920. return this._facetPartitioning;
  20921. };
  20922. /**
  20923. * Returns the i-th facet position in the world system.
  20924. * This method allocates a new Vector3 per call
  20925. * @param i defines the facet index
  20926. * @returns a new Vector3
  20927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20928. */
  20929. AbstractMesh.prototype.getFacetPosition = function (i) {
  20930. var pos = BABYLON.Vector3.Zero();
  20931. this.getFacetPositionToRef(i, pos);
  20932. return pos;
  20933. };
  20934. /**
  20935. * Sets the reference Vector3 with the i-th facet position in the world system
  20936. * @param i defines the facet index
  20937. * @param ref defines the target vector
  20938. * @returns the current mesh
  20939. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20940. */
  20941. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20942. var localPos = (this.getFacetLocalPositions())[i];
  20943. var world = this.getWorldMatrix();
  20944. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20945. return this;
  20946. };
  20947. /**
  20948. * Returns the i-th facet normal in the world system.
  20949. * This method allocates a new Vector3 per call
  20950. * @param i defines the facet index
  20951. * @returns a new Vector3
  20952. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20953. */
  20954. AbstractMesh.prototype.getFacetNormal = function (i) {
  20955. var norm = BABYLON.Vector3.Zero();
  20956. this.getFacetNormalToRef(i, norm);
  20957. return norm;
  20958. };
  20959. /**
  20960. * Sets the reference Vector3 with the i-th facet normal in the world system
  20961. * @param i defines the facet index
  20962. * @param ref defines the target vector
  20963. * @returns the current mesh
  20964. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20965. */
  20966. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20967. var localNorm = (this.getFacetLocalNormals())[i];
  20968. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20969. return this;
  20970. };
  20971. /**
  20972. * 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)
  20973. * @param x defines x coordinate
  20974. * @param y defines y coordinate
  20975. * @param z defines z coordinate
  20976. * @returns the array of facet indexes
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20980. var bInfo = this.getBoundingInfo();
  20981. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20982. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20983. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20984. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20985. return null;
  20986. }
  20987. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20988. };
  20989. /**
  20990. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20991. * @param projected sets as the (x,y,z) world projection on the facet
  20992. * @param checkFace if 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
  20993. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  20994. * @param x defines x coordinate
  20995. * @param y defines y coordinate
  20996. * @param z defines z coordinate
  20997. * @returns the face index if found (or null instead)
  20998. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20999. */
  21000. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21001. if (checkFace === void 0) { checkFace = false; }
  21002. if (facing === void 0) { facing = true; }
  21003. var world = this.getWorldMatrix();
  21004. var invMat = BABYLON.Tmp.Matrix[5];
  21005. world.invertToRef(invMat);
  21006. var invVect = BABYLON.Tmp.Vector3[8];
  21007. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21008. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21009. if (projected) {
  21010. // tranform the local computed projected vector to world coordinates
  21011. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21012. }
  21013. return closest;
  21014. };
  21015. /**
  21016. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21017. * @param projected sets as the (x,y,z) local projection on the facet
  21018. * @param checkFace if 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
  21019. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21020. * @param x defines x coordinate
  21021. * @param y defines y coordinate
  21022. * @param z defines z coordinate
  21023. * @returns the face index if found (or null instead)
  21024. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21025. */
  21026. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21027. if (checkFace === void 0) { checkFace = false; }
  21028. if (facing === void 0) { facing = true; }
  21029. var closest = null;
  21030. var tmpx = 0.0;
  21031. var tmpy = 0.0;
  21032. var tmpz = 0.0;
  21033. var d = 0.0; // tmp dot facet normal * facet position
  21034. var t0 = 0.0;
  21035. var projx = 0.0;
  21036. var projy = 0.0;
  21037. var projz = 0.0;
  21038. // Get all the facets in the same partitioning block than (x, y, z)
  21039. var facetPositions = this.getFacetLocalPositions();
  21040. var facetNormals = this.getFacetLocalNormals();
  21041. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21042. if (!facetsInBlock) {
  21043. return null;
  21044. }
  21045. // Get the closest facet to (x, y, z)
  21046. var shortest = Number.MAX_VALUE; // init distance vars
  21047. var tmpDistance = shortest;
  21048. var fib; // current facet in the block
  21049. var norm; // current facet normal
  21050. var p0; // current facet barycenter position
  21051. // loop on all the facets in the current partitioning block
  21052. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21053. fib = facetsInBlock[idx];
  21054. norm = facetNormals[fib];
  21055. p0 = facetPositions[fib];
  21056. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21057. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21058. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21059. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21060. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21061. projx = x + norm.x * t0;
  21062. projy = y + norm.y * t0;
  21063. projz = z + norm.z * t0;
  21064. tmpx = projx - x;
  21065. tmpy = projy - y;
  21066. tmpz = projz - z;
  21067. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21068. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21069. shortest = tmpDistance;
  21070. closest = fib;
  21071. if (projected) {
  21072. projected.x = projx;
  21073. projected.y = projy;
  21074. projected.z = projz;
  21075. }
  21076. }
  21077. }
  21078. }
  21079. return closest;
  21080. };
  21081. /**
  21082. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21083. * @returns the parameters
  21084. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21085. */
  21086. AbstractMesh.prototype.getFacetDataParameters = function () {
  21087. return this._facetParameters;
  21088. };
  21089. /**
  21090. * Disables the feature FacetData and frees the related memory
  21091. * @returns the current mesh
  21092. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21093. */
  21094. AbstractMesh.prototype.disableFacetData = function () {
  21095. if (this._facetDataEnabled) {
  21096. this._facetDataEnabled = false;
  21097. this._facetPositions = new Array();
  21098. this._facetNormals = new Array();
  21099. this._facetPartitioning = new Array();
  21100. this._facetParameters = null;
  21101. this._depthSortedIndices = new Uint32Array(0);
  21102. }
  21103. return this;
  21104. };
  21105. /**
  21106. * Updates the AbstractMesh indices array
  21107. * @param indices defines the data source
  21108. * @returns the current mesh
  21109. */
  21110. AbstractMesh.prototype.updateIndices = function (indices) {
  21111. return this;
  21112. };
  21113. /**
  21114. * Creates new normals data for the mesh
  21115. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21116. * @returns the current mesh
  21117. */
  21118. AbstractMesh.prototype.createNormals = function (updatable) {
  21119. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21120. var indices = this.getIndices();
  21121. var normals;
  21122. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21123. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21124. }
  21125. else {
  21126. normals = [];
  21127. }
  21128. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21129. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21130. return this;
  21131. };
  21132. /**
  21133. * Align the mesh with a normal
  21134. * @param normal defines the normal to use
  21135. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21136. * @returns the current mesh
  21137. */
  21138. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21139. if (!upDirection) {
  21140. upDirection = BABYLON.Axis.Y;
  21141. }
  21142. var axisX = BABYLON.Tmp.Vector3[0];
  21143. var axisZ = BABYLON.Tmp.Vector3[1];
  21144. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21145. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21146. if (this.rotationQuaternion) {
  21147. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21148. }
  21149. else {
  21150. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21151. }
  21152. return this;
  21153. };
  21154. /** @hidden */
  21155. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21156. var engine = this.getEngine();
  21157. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21158. this._isOccluded = false;
  21159. return;
  21160. }
  21161. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21162. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21163. if (isOcclusionQueryAvailable) {
  21164. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21165. this._isOcclusionQueryInProgress = false;
  21166. this._occlusionInternalRetryCounter = 0;
  21167. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21168. }
  21169. else {
  21170. this._occlusionInternalRetryCounter++;
  21171. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21172. this._isOcclusionQueryInProgress = false;
  21173. this._occlusionInternalRetryCounter = 0;
  21174. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21175. // if strict continue the last state of the object.
  21176. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21177. }
  21178. else {
  21179. return;
  21180. }
  21181. }
  21182. }
  21183. var scene = this.getScene();
  21184. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21185. if (!this._occlusionQuery) {
  21186. this._occlusionQuery = engine.createQuery();
  21187. }
  21188. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21189. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21190. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21191. this._isOcclusionQueryInProgress = true;
  21192. };
  21193. /** No occlusion */
  21194. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21195. /** Occlusion set to optimisitic */
  21196. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21197. /** Occlusion set to strict */
  21198. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21199. /** Use an accurante occlusion algorithm */
  21200. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21201. /** Use a conservative occlusion algorithm */
  21202. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21203. return AbstractMesh;
  21204. }(BABYLON.TransformNode));
  21205. BABYLON.AbstractMesh = AbstractMesh;
  21206. })(BABYLON || (BABYLON = {}));
  21207. //# sourceMappingURL=babylon.abstractMesh.js.map
  21208. var BABYLON;
  21209. (function (BABYLON) {
  21210. /**
  21211. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21212. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21213. * 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.
  21214. */
  21215. var Light = /** @class */ (function (_super) {
  21216. __extends(Light, _super);
  21217. /**
  21218. * Creates a Light object in the scene.
  21219. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21220. * @param name The firendly name of the light
  21221. * @param scene The scene the light belongs too
  21222. */
  21223. function Light(name, scene) {
  21224. var _this = _super.call(this, name, scene) || this;
  21225. /**
  21226. * Diffuse gives the basic color to an object.
  21227. */
  21228. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21229. /**
  21230. * Specular produces a highlight color on an object.
  21231. * Note: This is note affecting PBR materials.
  21232. */
  21233. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21234. /**
  21235. * Strength of the light.
  21236. * Note: By default it is define in the framework own unit.
  21237. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21238. */
  21239. _this.intensity = 1.0;
  21240. /**
  21241. * Defines how far from the source the light is impacting in scene units.
  21242. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21243. */
  21244. _this.range = Number.MAX_VALUE;
  21245. /**
  21246. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21247. * of light.
  21248. */
  21249. _this._photometricScale = 1.0;
  21250. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21251. _this._radius = 0.00001;
  21252. /**
  21253. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21254. * exceeding the number allowed of the materials.
  21255. */
  21256. _this.renderPriority = 0;
  21257. /**
  21258. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21259. * the current shadow generator.
  21260. */
  21261. _this.shadowEnabled = true;
  21262. _this._excludeWithLayerMask = 0;
  21263. _this._includeOnlyWithLayerMask = 0;
  21264. _this._lightmapMode = 0;
  21265. /**
  21266. * @hidden Internal use only.
  21267. */
  21268. _this._excludedMeshesIds = new Array();
  21269. /**
  21270. * @hidden Internal use only.
  21271. */
  21272. _this._includedOnlyMeshesIds = new Array();
  21273. _this.getScene().addLight(_this);
  21274. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21275. _this._buildUniformLayout();
  21276. _this.includedOnlyMeshes = new Array();
  21277. _this.excludedMeshes = new Array();
  21278. _this._resyncMeshes();
  21279. return _this;
  21280. }
  21281. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21282. /**
  21283. * If every light affecting the material is in this lightmapMode,
  21284. * material.lightmapTexture adds or multiplies
  21285. * (depends on material.useLightmapAsShadowmap)
  21286. * after every other light calculations.
  21287. */
  21288. get: function () {
  21289. return Light._LIGHTMAP_DEFAULT;
  21290. },
  21291. enumerable: true,
  21292. configurable: true
  21293. });
  21294. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21295. /**
  21296. * material.lightmapTexture as only diffuse lighting from this light
  21297. * adds only specular lighting from this light
  21298. * adds dynamic shadows
  21299. */
  21300. get: function () {
  21301. return Light._LIGHTMAP_SPECULAR;
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21307. /**
  21308. * material.lightmapTexture as only lighting
  21309. * no light calculation from this light
  21310. * only adds dynamic shadows from this light
  21311. */
  21312. get: function () {
  21313. return Light._LIGHTMAP_SHADOWSONLY;
  21314. },
  21315. enumerable: true,
  21316. configurable: true
  21317. });
  21318. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21319. /**
  21320. * Each light type uses the default quantity according to its type:
  21321. * point/spot lights use luminous intensity
  21322. * directional lights use illuminance
  21323. */
  21324. get: function () {
  21325. return Light._INTENSITYMODE_AUTOMATIC;
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21331. /**
  21332. * lumen (lm)
  21333. */
  21334. get: function () {
  21335. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21336. },
  21337. enumerable: true,
  21338. configurable: true
  21339. });
  21340. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21341. /**
  21342. * candela (lm/sr)
  21343. */
  21344. get: function () {
  21345. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21346. },
  21347. enumerable: true,
  21348. configurable: true
  21349. });
  21350. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21351. /**
  21352. * lux (lm/m^2)
  21353. */
  21354. get: function () {
  21355. return Light._INTENSITYMODE_ILLUMINANCE;
  21356. },
  21357. enumerable: true,
  21358. configurable: true
  21359. });
  21360. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21361. /**
  21362. * nit (cd/m^2)
  21363. */
  21364. get: function () {
  21365. return Light._INTENSITYMODE_LUMINANCE;
  21366. },
  21367. enumerable: true,
  21368. configurable: true
  21369. });
  21370. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21371. /**
  21372. * Light type const id of the point light.
  21373. */
  21374. get: function () {
  21375. return Light._LIGHTTYPEID_POINTLIGHT;
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21381. /**
  21382. * Light type const id of the directional light.
  21383. */
  21384. get: function () {
  21385. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21391. /**
  21392. * Light type const id of the spot light.
  21393. */
  21394. get: function () {
  21395. return Light._LIGHTTYPEID_SPOTLIGHT;
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21401. /**
  21402. * Light type const id of the hemispheric light.
  21403. */
  21404. get: function () {
  21405. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Light.prototype, "intensityMode", {
  21411. /**
  21412. * Gets the photometric scale used to interpret the intensity.
  21413. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21414. */
  21415. get: function () {
  21416. return this._intensityMode;
  21417. },
  21418. /**
  21419. * Sets the photometric scale used to interpret the intensity.
  21420. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21421. */
  21422. set: function (value) {
  21423. this._intensityMode = value;
  21424. this._computePhotometricScale();
  21425. },
  21426. enumerable: true,
  21427. configurable: true
  21428. });
  21429. ;
  21430. ;
  21431. Object.defineProperty(Light.prototype, "radius", {
  21432. /**
  21433. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21434. */
  21435. get: function () {
  21436. return this._radius;
  21437. },
  21438. /**
  21439. * sets the light radius used by PBR Materials to simulate soft area lights.
  21440. */
  21441. set: function (value) {
  21442. this._radius = value;
  21443. this._computePhotometricScale();
  21444. },
  21445. enumerable: true,
  21446. configurable: true
  21447. });
  21448. ;
  21449. ;
  21450. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21451. /**
  21452. * Gets the only meshes impacted by this light.
  21453. */
  21454. get: function () {
  21455. return this._includedOnlyMeshes;
  21456. },
  21457. /**
  21458. * Sets the only meshes impacted by this light.
  21459. */
  21460. set: function (value) {
  21461. this._includedOnlyMeshes = value;
  21462. this._hookArrayForIncludedOnly(value);
  21463. },
  21464. enumerable: true,
  21465. configurable: true
  21466. });
  21467. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21468. /**
  21469. * Gets the meshes not impacted by this light.
  21470. */
  21471. get: function () {
  21472. return this._excludedMeshes;
  21473. },
  21474. /**
  21475. * Sets the meshes not impacted by this light.
  21476. */
  21477. set: function (value) {
  21478. this._excludedMeshes = value;
  21479. this._hookArrayForExcluded(value);
  21480. },
  21481. enumerable: true,
  21482. configurable: true
  21483. });
  21484. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21485. /**
  21486. * Gets the layer id use to find what meshes are not impacted by the light.
  21487. * Inactive if 0
  21488. */
  21489. get: function () {
  21490. return this._excludeWithLayerMask;
  21491. },
  21492. /**
  21493. * Sets the layer id use to find what meshes are not impacted by the light.
  21494. * Inactive if 0
  21495. */
  21496. set: function (value) {
  21497. this._excludeWithLayerMask = value;
  21498. this._resyncMeshes();
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21504. /**
  21505. * Gets the layer id use to find what meshes are impacted by the light.
  21506. * Inactive if 0
  21507. */
  21508. get: function () {
  21509. return this._includeOnlyWithLayerMask;
  21510. },
  21511. /**
  21512. * Sets the layer id use to find what meshes are impacted by the light.
  21513. * Inactive if 0
  21514. */
  21515. set: function (value) {
  21516. this._includeOnlyWithLayerMask = value;
  21517. this._resyncMeshes();
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(Light.prototype, "lightmapMode", {
  21523. /**
  21524. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21525. */
  21526. get: function () {
  21527. return this._lightmapMode;
  21528. },
  21529. /**
  21530. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21531. */
  21532. set: function (value) {
  21533. if (this._lightmapMode === value) {
  21534. return;
  21535. }
  21536. this._lightmapMode = value;
  21537. this._markMeshesAsLightDirty();
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. /**
  21543. * Returns the string "Light".
  21544. * @returns the class name
  21545. */
  21546. Light.prototype.getClassName = function () {
  21547. return "Light";
  21548. };
  21549. /**
  21550. * Converts the light information to a readable string for debug purpose.
  21551. * @param fullDetails Supports for multiple levels of logging within scene loading
  21552. * @returns the human readable light info
  21553. */
  21554. Light.prototype.toString = function (fullDetails) {
  21555. var ret = "Name: " + this.name;
  21556. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21557. if (this.animations) {
  21558. for (var i = 0; i < this.animations.length; i++) {
  21559. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21560. }
  21561. }
  21562. if (fullDetails) {
  21563. }
  21564. return ret;
  21565. };
  21566. /**
  21567. * Set the enabled state of this node.
  21568. * @param value - the new enabled state
  21569. */
  21570. Light.prototype.setEnabled = function (value) {
  21571. _super.prototype.setEnabled.call(this, value);
  21572. this._resyncMeshes();
  21573. };
  21574. /**
  21575. * Returns the Light associated shadow generator if any.
  21576. * @return the associated shadow generator.
  21577. */
  21578. Light.prototype.getShadowGenerator = function () {
  21579. return this._shadowGenerator;
  21580. };
  21581. /**
  21582. * Returns a Vector3, the absolute light position in the World.
  21583. * @returns the world space position of the light
  21584. */
  21585. Light.prototype.getAbsolutePosition = function () {
  21586. return BABYLON.Vector3.Zero();
  21587. };
  21588. /**
  21589. * Specifies if the light will affect the passed mesh.
  21590. * @param mesh The mesh to test against the light
  21591. * @return true the mesh is affected otherwise, false.
  21592. */
  21593. Light.prototype.canAffectMesh = function (mesh) {
  21594. if (!mesh) {
  21595. return true;
  21596. }
  21597. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21598. return false;
  21599. }
  21600. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21601. return false;
  21602. }
  21603. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21604. return false;
  21605. }
  21606. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21607. return false;
  21608. }
  21609. return true;
  21610. };
  21611. /**
  21612. * Computes and Returns the light World matrix.
  21613. * @returns the world matrix
  21614. */
  21615. Light.prototype.getWorldMatrix = function () {
  21616. this._currentRenderId = this.getScene().getRenderId();
  21617. this._childRenderId = this._currentRenderId;
  21618. var worldMatrix = this._getWorldMatrix();
  21619. if (this.parent && this.parent.getWorldMatrix) {
  21620. if (!this._parentedWorldMatrix) {
  21621. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21622. }
  21623. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21624. this._markSyncedWithParent();
  21625. return this._parentedWorldMatrix;
  21626. }
  21627. return worldMatrix;
  21628. };
  21629. /**
  21630. * Sort function to order lights for rendering.
  21631. * @param a First Light object to compare to second.
  21632. * @param b Second Light object to compare first.
  21633. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21634. */
  21635. Light.CompareLightsPriority = function (a, b) {
  21636. //shadow-casting lights have priority over non-shadow-casting lights
  21637. //the renderPrioirty is a secondary sort criterion
  21638. if (a.shadowEnabled !== b.shadowEnabled) {
  21639. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21640. }
  21641. return b.renderPriority - a.renderPriority;
  21642. };
  21643. /**
  21644. * Releases resources associated with this node.
  21645. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21646. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21647. */
  21648. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21649. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21650. if (this._shadowGenerator) {
  21651. this._shadowGenerator.dispose();
  21652. this._shadowGenerator = null;
  21653. }
  21654. // Animations
  21655. this.getScene().stopAnimation(this);
  21656. // Remove from meshes
  21657. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21658. var mesh = _a[_i];
  21659. mesh._removeLightSource(this);
  21660. }
  21661. this._uniformBuffer.dispose();
  21662. // Remove from scene
  21663. this.getScene().removeLight(this);
  21664. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21665. };
  21666. /**
  21667. * Returns the light type ID (integer).
  21668. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21669. */
  21670. Light.prototype.getTypeID = function () {
  21671. return 0;
  21672. };
  21673. /**
  21674. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21675. * @returns the scaled intensity in intensity mode unit
  21676. */
  21677. Light.prototype.getScaledIntensity = function () {
  21678. return this._photometricScale * this.intensity;
  21679. };
  21680. /**
  21681. * Returns a new Light object, named "name", from the current one.
  21682. * @param name The name of the cloned light
  21683. * @returns the new created light
  21684. */
  21685. Light.prototype.clone = function (name) {
  21686. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21687. if (!constructor) {
  21688. return null;
  21689. }
  21690. return BABYLON.SerializationHelper.Clone(constructor, this);
  21691. };
  21692. /**
  21693. * Serializes the current light into a Serialization object.
  21694. * @returns the serialized object.
  21695. */
  21696. Light.prototype.serialize = function () {
  21697. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21698. // Type
  21699. serializationObject.type = this.getTypeID();
  21700. // Parent
  21701. if (this.parent) {
  21702. serializationObject.parentId = this.parent.id;
  21703. }
  21704. // Inclusion / exclusions
  21705. if (this.excludedMeshes.length > 0) {
  21706. serializationObject.excludedMeshesIds = [];
  21707. this.excludedMeshes.forEach(function (mesh) {
  21708. serializationObject.excludedMeshesIds.push(mesh.id);
  21709. });
  21710. }
  21711. if (this.includedOnlyMeshes.length > 0) {
  21712. serializationObject.includedOnlyMeshesIds = [];
  21713. this.includedOnlyMeshes.forEach(function (mesh) {
  21714. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21715. });
  21716. }
  21717. // Animations
  21718. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21719. serializationObject.ranges = this.serializeAnimationRanges();
  21720. return serializationObject;
  21721. };
  21722. /**
  21723. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21724. * This new light is named "name" and added to the passed scene.
  21725. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21726. * @param name The friendly name of the light
  21727. * @param scene The scene the new light will belong to
  21728. * @returns the constructor function
  21729. */
  21730. Light.GetConstructorFromName = function (type, name, scene) {
  21731. switch (type) {
  21732. case 0:
  21733. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21734. case 1:
  21735. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21736. case 2:
  21737. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21738. case 3:
  21739. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21740. }
  21741. return null;
  21742. };
  21743. /**
  21744. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21745. * @param parsedLight The JSON representation of the light
  21746. * @param scene The scene to create the parsed light in
  21747. * @returns the created light after parsing
  21748. */
  21749. Light.Parse = function (parsedLight, scene) {
  21750. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21751. if (!constructor) {
  21752. return null;
  21753. }
  21754. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21755. // Inclusion / exclusions
  21756. if (parsedLight.excludedMeshesIds) {
  21757. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21758. }
  21759. if (parsedLight.includedOnlyMeshesIds) {
  21760. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21761. }
  21762. // Parent
  21763. if (parsedLight.parentId) {
  21764. light._waitingParentId = parsedLight.parentId;
  21765. }
  21766. // Animations
  21767. if (parsedLight.animations) {
  21768. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21769. var parsedAnimation = parsedLight.animations[animationIndex];
  21770. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21771. }
  21772. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21773. }
  21774. if (parsedLight.autoAnimate) {
  21775. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21776. }
  21777. return light;
  21778. };
  21779. Light.prototype._hookArrayForExcluded = function (array) {
  21780. var _this = this;
  21781. var oldPush = array.push;
  21782. array.push = function () {
  21783. var items = [];
  21784. for (var _i = 0; _i < arguments.length; _i++) {
  21785. items[_i] = arguments[_i];
  21786. }
  21787. var result = oldPush.apply(array, items);
  21788. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21789. var item = items_1[_a];
  21790. item._resyncLighSource(_this);
  21791. }
  21792. return result;
  21793. };
  21794. var oldSplice = array.splice;
  21795. array.splice = function (index, deleteCount) {
  21796. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21797. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21798. var item = deleted_1[_i];
  21799. item._resyncLighSource(_this);
  21800. }
  21801. return deleted;
  21802. };
  21803. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21804. var item = array_1[_i];
  21805. item._resyncLighSource(this);
  21806. }
  21807. };
  21808. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21809. var _this = this;
  21810. var oldPush = array.push;
  21811. array.push = function () {
  21812. var items = [];
  21813. for (var _i = 0; _i < arguments.length; _i++) {
  21814. items[_i] = arguments[_i];
  21815. }
  21816. var result = oldPush.apply(array, items);
  21817. _this._resyncMeshes();
  21818. return result;
  21819. };
  21820. var oldSplice = array.splice;
  21821. array.splice = function (index, deleteCount) {
  21822. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21823. _this._resyncMeshes();
  21824. return deleted;
  21825. };
  21826. this._resyncMeshes();
  21827. };
  21828. Light.prototype._resyncMeshes = function () {
  21829. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21830. var mesh = _a[_i];
  21831. mesh._resyncLighSource(this);
  21832. }
  21833. };
  21834. /**
  21835. * Forces the meshes to update their light related information in their rendering used effects
  21836. * @hidden Internal Use Only
  21837. */
  21838. Light.prototype._markMeshesAsLightDirty = function () {
  21839. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21840. var mesh = _a[_i];
  21841. if (mesh._lightSources.indexOf(this) !== -1) {
  21842. mesh._markSubMeshesAsLightDirty();
  21843. }
  21844. }
  21845. };
  21846. /**
  21847. * Recomputes the cached photometric scale if needed.
  21848. */
  21849. Light.prototype._computePhotometricScale = function () {
  21850. this._photometricScale = this._getPhotometricScale();
  21851. this.getScene().resetCachedMaterial();
  21852. };
  21853. /**
  21854. * Returns the Photometric Scale according to the light type and intensity mode.
  21855. */
  21856. Light.prototype._getPhotometricScale = function () {
  21857. var photometricScale = 0.0;
  21858. var lightTypeID = this.getTypeID();
  21859. //get photometric mode
  21860. var photometricMode = this.intensityMode;
  21861. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21862. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21863. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21864. }
  21865. else {
  21866. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21867. }
  21868. }
  21869. //compute photometric scale
  21870. switch (lightTypeID) {
  21871. case Light.LIGHTTYPEID_POINTLIGHT:
  21872. case Light.LIGHTTYPEID_SPOTLIGHT:
  21873. switch (photometricMode) {
  21874. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21875. photometricScale = 1.0 / (4.0 * Math.PI);
  21876. break;
  21877. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21878. photometricScale = 1.0;
  21879. break;
  21880. case Light.INTENSITYMODE_LUMINANCE:
  21881. photometricScale = this.radius * this.radius;
  21882. break;
  21883. }
  21884. break;
  21885. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21886. switch (photometricMode) {
  21887. case Light.INTENSITYMODE_ILLUMINANCE:
  21888. photometricScale = 1.0;
  21889. break;
  21890. case Light.INTENSITYMODE_LUMINANCE:
  21891. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21892. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21893. var apexAngleRadians = this.radius;
  21894. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21895. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21896. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21897. photometricScale = solidAngle;
  21898. break;
  21899. }
  21900. break;
  21901. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21902. // No fall off in hemisperic light.
  21903. photometricScale = 1.0;
  21904. break;
  21905. }
  21906. return photometricScale;
  21907. };
  21908. /**
  21909. * Reorder the light in the scene according to their defined priority.
  21910. * @hidden Internal Use Only
  21911. */
  21912. Light.prototype._reorderLightsInScene = function () {
  21913. var scene = this.getScene();
  21914. if (this._renderPriority != 0) {
  21915. scene.requireLightSorting = true;
  21916. }
  21917. this.getScene().sortLightsByPriority();
  21918. };
  21919. //lightmapMode Consts
  21920. Light._LIGHTMAP_DEFAULT = 0;
  21921. Light._LIGHTMAP_SPECULAR = 1;
  21922. Light._LIGHTMAP_SHADOWSONLY = 2;
  21923. // Intensity Mode Consts
  21924. Light._INTENSITYMODE_AUTOMATIC = 0;
  21925. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21926. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21927. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21928. Light._INTENSITYMODE_LUMINANCE = 4;
  21929. // Light types ids const.
  21930. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21931. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21932. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21933. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21934. __decorate([
  21935. BABYLON.serializeAsColor3()
  21936. ], Light.prototype, "diffuse", void 0);
  21937. __decorate([
  21938. BABYLON.serializeAsColor3()
  21939. ], Light.prototype, "specular", void 0);
  21940. __decorate([
  21941. BABYLON.serialize()
  21942. ], Light.prototype, "intensity", void 0);
  21943. __decorate([
  21944. BABYLON.serialize()
  21945. ], Light.prototype, "range", void 0);
  21946. __decorate([
  21947. BABYLON.serialize()
  21948. ], Light.prototype, "intensityMode", null);
  21949. __decorate([
  21950. BABYLON.serialize()
  21951. ], Light.prototype, "radius", null);
  21952. __decorate([
  21953. BABYLON.serialize()
  21954. ], Light.prototype, "_renderPriority", void 0);
  21955. __decorate([
  21956. BABYLON.expandToProperty("_reorderLightsInScene")
  21957. ], Light.prototype, "renderPriority", void 0);
  21958. __decorate([
  21959. BABYLON.serialize()
  21960. ], Light.prototype, "shadowEnabled", void 0);
  21961. __decorate([
  21962. BABYLON.serialize("excludeWithLayerMask")
  21963. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21964. __decorate([
  21965. BABYLON.serialize("includeOnlyWithLayerMask")
  21966. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21967. __decorate([
  21968. BABYLON.serialize("lightmapMode")
  21969. ], Light.prototype, "_lightmapMode", void 0);
  21970. return Light;
  21971. }(BABYLON.Node));
  21972. BABYLON.Light = Light;
  21973. })(BABYLON || (BABYLON = {}));
  21974. //# sourceMappingURL=babylon.light.js.map
  21975. var BABYLON;
  21976. (function (BABYLON) {
  21977. var Camera = /** @class */ (function (_super) {
  21978. __extends(Camera, _super);
  21979. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21980. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21981. var _this = _super.call(this, name, scene) || this;
  21982. /**
  21983. * The vector the camera should consider as up.
  21984. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21985. */
  21986. _this.upVector = BABYLON.Vector3.Up();
  21987. _this.orthoLeft = null;
  21988. _this.orthoRight = null;
  21989. _this.orthoBottom = null;
  21990. _this.orthoTop = null;
  21991. /**
  21992. * FOV is set in Radians. (default is 0.8)
  21993. */
  21994. _this.fov = 0.8;
  21995. _this.minZ = 1;
  21996. _this.maxZ = 10000.0;
  21997. _this.inertia = 0.9;
  21998. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21999. _this.isIntermediate = false;
  22000. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22001. /**
  22002. * Restricts the camera to viewing objects with the same layerMask.
  22003. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22004. */
  22005. _this.layerMask = 0x0FFFFFFF;
  22006. /**
  22007. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22008. */
  22009. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22010. // Camera rig members
  22011. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22012. _this._rigCameras = new Array();
  22013. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22014. _this._skipRendering = false;
  22015. _this.customRenderTargets = new Array();
  22016. // Observables
  22017. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22018. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22019. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22020. _this.onRestoreStateObservable = new BABYLON.Observable();
  22021. // Cache
  22022. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22023. _this._projectionMatrix = new BABYLON.Matrix();
  22024. _this._doNotComputeProjectionMatrix = false;
  22025. _this._worldMatrix = BABYLON.Matrix.Identity();
  22026. _this._postProcesses = new Array();
  22027. _this._transformMatrix = BABYLON.Matrix.Zero();
  22028. _this._activeMeshes = new BABYLON.SmartArray(256);
  22029. _this._globalPosition = BABYLON.Vector3.Zero();
  22030. _this._refreshFrustumPlanes = true;
  22031. _this.getScene().addCamera(_this);
  22032. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22033. _this.getScene().activeCamera = _this;
  22034. }
  22035. _this.position = position;
  22036. return _this;
  22037. }
  22038. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22039. get: function () {
  22040. return Camera._PERSPECTIVE_CAMERA;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22046. get: function () {
  22047. return Camera._ORTHOGRAPHIC_CAMERA;
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22053. /**
  22054. * This is the default FOV mode for perspective cameras.
  22055. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22056. *
  22057. */
  22058. get: function () {
  22059. return Camera._FOVMODE_VERTICAL_FIXED;
  22060. },
  22061. enumerable: true,
  22062. configurable: true
  22063. });
  22064. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22065. /**
  22066. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22067. *
  22068. */
  22069. get: function () {
  22070. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22076. get: function () {
  22077. return Camera._RIG_MODE_NONE;
  22078. },
  22079. enumerable: true,
  22080. configurable: true
  22081. });
  22082. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22083. get: function () {
  22084. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22090. get: function () {
  22091. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22097. get: function () {
  22098. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22099. },
  22100. enumerable: true,
  22101. configurable: true
  22102. });
  22103. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22104. get: function () {
  22105. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22106. },
  22107. enumerable: true,
  22108. configurable: true
  22109. });
  22110. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22111. get: function () {
  22112. return Camera._RIG_MODE_VR;
  22113. },
  22114. enumerable: true,
  22115. configurable: true
  22116. });
  22117. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22118. get: function () {
  22119. return Camera._RIG_MODE_WEBVR;
  22120. },
  22121. enumerable: true,
  22122. configurable: true
  22123. });
  22124. /**
  22125. * Store current camera state (fov, position, etc..)
  22126. */
  22127. Camera.prototype.storeState = function () {
  22128. this._stateStored = true;
  22129. this._storedFov = this.fov;
  22130. return this;
  22131. };
  22132. /**
  22133. * Restores the camera state values if it has been stored. You must call storeState() first
  22134. */
  22135. Camera.prototype._restoreStateValues = function () {
  22136. if (!this._stateStored) {
  22137. return false;
  22138. }
  22139. this.fov = this._storedFov;
  22140. return true;
  22141. };
  22142. /**
  22143. * Restored camera state. You must call storeState() first
  22144. */
  22145. Camera.prototype.restoreState = function () {
  22146. if (this._restoreStateValues()) {
  22147. this.onRestoreStateObservable.notifyObservers(this);
  22148. return true;
  22149. }
  22150. return false;
  22151. };
  22152. Camera.prototype.getClassName = function () {
  22153. return "Camera";
  22154. };
  22155. /**
  22156. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22157. */
  22158. Camera.prototype.toString = function (fullDetails) {
  22159. var ret = "Name: " + this.name;
  22160. ret += ", type: " + this.getClassName();
  22161. if (this.animations) {
  22162. for (var i = 0; i < this.animations.length; i++) {
  22163. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22164. }
  22165. }
  22166. if (fullDetails) {
  22167. }
  22168. return ret;
  22169. };
  22170. Object.defineProperty(Camera.prototype, "globalPosition", {
  22171. get: function () {
  22172. return this._globalPosition;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Camera.prototype.getActiveMeshes = function () {
  22178. return this._activeMeshes;
  22179. };
  22180. Camera.prototype.isActiveMesh = function (mesh) {
  22181. return (this._activeMeshes.indexOf(mesh) !== -1);
  22182. };
  22183. /**
  22184. * Is this camera ready to be used/rendered
  22185. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22186. * @return true if the camera is ready
  22187. */
  22188. Camera.prototype.isReady = function (completeCheck) {
  22189. if (completeCheck === void 0) { completeCheck = false; }
  22190. if (completeCheck) {
  22191. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22192. var pp = _a[_i];
  22193. if (pp && !pp.isReady()) {
  22194. return false;
  22195. }
  22196. }
  22197. }
  22198. return _super.prototype.isReady.call(this, completeCheck);
  22199. };
  22200. //Cache
  22201. Camera.prototype._initCache = function () {
  22202. _super.prototype._initCache.call(this);
  22203. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22204. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22205. this._cache.mode = undefined;
  22206. this._cache.minZ = undefined;
  22207. this._cache.maxZ = undefined;
  22208. this._cache.fov = undefined;
  22209. this._cache.fovMode = undefined;
  22210. this._cache.aspectRatio = undefined;
  22211. this._cache.orthoLeft = undefined;
  22212. this._cache.orthoRight = undefined;
  22213. this._cache.orthoBottom = undefined;
  22214. this._cache.orthoTop = undefined;
  22215. this._cache.renderWidth = undefined;
  22216. this._cache.renderHeight = undefined;
  22217. };
  22218. Camera.prototype._updateCache = function (ignoreParentClass) {
  22219. if (!ignoreParentClass) {
  22220. _super.prototype._updateCache.call(this);
  22221. }
  22222. this._cache.position.copyFrom(this.position);
  22223. this._cache.upVector.copyFrom(this.upVector);
  22224. };
  22225. // Synchronized
  22226. Camera.prototype._isSynchronized = function () {
  22227. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22228. };
  22229. Camera.prototype._isSynchronizedViewMatrix = function () {
  22230. if (!_super.prototype._isSynchronized.call(this))
  22231. return false;
  22232. return this._cache.position.equals(this.position)
  22233. && this._cache.upVector.equals(this.upVector)
  22234. && this.isSynchronizedWithParent();
  22235. };
  22236. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22237. var check = this._cache.mode === this.mode
  22238. && this._cache.minZ === this.minZ
  22239. && this._cache.maxZ === this.maxZ;
  22240. if (!check) {
  22241. return false;
  22242. }
  22243. var engine = this.getEngine();
  22244. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22245. check = this._cache.fov === this.fov
  22246. && this._cache.fovMode === this.fovMode
  22247. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22248. }
  22249. else {
  22250. check = this._cache.orthoLeft === this.orthoLeft
  22251. && this._cache.orthoRight === this.orthoRight
  22252. && this._cache.orthoBottom === this.orthoBottom
  22253. && this._cache.orthoTop === this.orthoTop
  22254. && this._cache.renderWidth === engine.getRenderWidth()
  22255. && this._cache.renderHeight === engine.getRenderHeight();
  22256. }
  22257. return check;
  22258. };
  22259. // Controls
  22260. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22261. };
  22262. Camera.prototype.detachControl = function (element) {
  22263. };
  22264. Camera.prototype.update = function () {
  22265. this._checkInputs();
  22266. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22267. this._updateRigCameras();
  22268. }
  22269. };
  22270. Camera.prototype._checkInputs = function () {
  22271. this.onAfterCheckInputsObservable.notifyObservers(this);
  22272. };
  22273. Object.defineProperty(Camera.prototype, "rigCameras", {
  22274. get: function () {
  22275. return this._rigCameras;
  22276. },
  22277. enumerable: true,
  22278. configurable: true
  22279. });
  22280. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22281. get: function () {
  22282. return this._rigPostProcess;
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. /**
  22288. * Internal, gets the first post proces.
  22289. * @returns the first post process to be run on this camera.
  22290. */
  22291. Camera.prototype._getFirstPostProcess = function () {
  22292. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22293. if (this._postProcesses[ppIndex] !== null) {
  22294. return this._postProcesses[ppIndex];
  22295. }
  22296. }
  22297. return null;
  22298. };
  22299. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22300. // invalidate framebuffer
  22301. var firstPostProcess = this._getFirstPostProcess();
  22302. if (firstPostProcess) {
  22303. firstPostProcess.markTextureDirty();
  22304. }
  22305. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22306. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22307. var cam = this._rigCameras[i];
  22308. var rigPostProcess = cam._rigPostProcess;
  22309. // for VR rig, there does not have to be a post process
  22310. if (rigPostProcess) {
  22311. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22312. if (isPass) {
  22313. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22314. cam.isIntermediate = this._postProcesses.length === 0;
  22315. }
  22316. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22317. rigPostProcess.markTextureDirty();
  22318. }
  22319. else {
  22320. cam._postProcesses = this._postProcesses.slice(0);
  22321. }
  22322. }
  22323. };
  22324. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22325. if (insertAt === void 0) { insertAt = null; }
  22326. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22327. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22328. return 0;
  22329. }
  22330. if (insertAt == null || insertAt < 0) {
  22331. this._postProcesses.push(postProcess);
  22332. }
  22333. else if (this._postProcesses[insertAt] === null) {
  22334. this._postProcesses[insertAt] = postProcess;
  22335. }
  22336. else {
  22337. this._postProcesses.splice(insertAt, 0, postProcess);
  22338. }
  22339. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22340. return this._postProcesses.indexOf(postProcess);
  22341. };
  22342. Camera.prototype.detachPostProcess = function (postProcess) {
  22343. var idx = this._postProcesses.indexOf(postProcess);
  22344. if (idx !== -1) {
  22345. this._postProcesses[idx] = null;
  22346. }
  22347. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22348. };
  22349. Camera.prototype.getWorldMatrix = function () {
  22350. if (this._isSynchronizedViewMatrix()) {
  22351. return this._worldMatrix;
  22352. }
  22353. // Getting the the view matrix will also compute the world matrix.
  22354. this.getViewMatrix();
  22355. return this._worldMatrix;
  22356. };
  22357. Camera.prototype._getViewMatrix = function () {
  22358. return BABYLON.Matrix.Identity();
  22359. };
  22360. Camera.prototype.getViewMatrix = function (force) {
  22361. if (!force && this._isSynchronizedViewMatrix()) {
  22362. return this._computedViewMatrix;
  22363. }
  22364. this.updateCache();
  22365. this._computedViewMatrix = this._getViewMatrix();
  22366. this._currentRenderId = this.getScene().getRenderId();
  22367. this._childRenderId = this._currentRenderId;
  22368. this._refreshFrustumPlanes = true;
  22369. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22370. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22371. }
  22372. this.onViewMatrixChangedObservable.notifyObservers(this);
  22373. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22374. return this._computedViewMatrix;
  22375. };
  22376. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22377. this._doNotComputeProjectionMatrix = true;
  22378. if (projection !== undefined) {
  22379. this._projectionMatrix = projection;
  22380. }
  22381. };
  22382. ;
  22383. Camera.prototype.unfreezeProjectionMatrix = function () {
  22384. this._doNotComputeProjectionMatrix = false;
  22385. };
  22386. ;
  22387. Camera.prototype.getProjectionMatrix = function (force) {
  22388. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22389. return this._projectionMatrix;
  22390. }
  22391. // Cache
  22392. this._cache.mode = this.mode;
  22393. this._cache.minZ = this.minZ;
  22394. this._cache.maxZ = this.maxZ;
  22395. // Matrix
  22396. this._refreshFrustumPlanes = true;
  22397. var engine = this.getEngine();
  22398. var scene = this.getScene();
  22399. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22400. this._cache.fov = this.fov;
  22401. this._cache.fovMode = this.fovMode;
  22402. this._cache.aspectRatio = engine.getAspectRatio(this);
  22403. if (this.minZ <= 0) {
  22404. this.minZ = 0.1;
  22405. }
  22406. if (scene.useRightHandedSystem) {
  22407. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22408. }
  22409. else {
  22410. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22411. }
  22412. }
  22413. else {
  22414. var halfWidth = engine.getRenderWidth() / 2.0;
  22415. var halfHeight = engine.getRenderHeight() / 2.0;
  22416. if (scene.useRightHandedSystem) {
  22417. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22418. }
  22419. else {
  22420. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22421. }
  22422. this._cache.orthoLeft = this.orthoLeft;
  22423. this._cache.orthoRight = this.orthoRight;
  22424. this._cache.orthoBottom = this.orthoBottom;
  22425. this._cache.orthoTop = this.orthoTop;
  22426. this._cache.renderWidth = engine.getRenderWidth();
  22427. this._cache.renderHeight = engine.getRenderHeight();
  22428. }
  22429. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22430. return this._projectionMatrix;
  22431. };
  22432. Camera.prototype.getTranformationMatrix = function () {
  22433. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22434. return this._transformMatrix;
  22435. };
  22436. Camera.prototype.updateFrustumPlanes = function () {
  22437. if (!this._refreshFrustumPlanes) {
  22438. return;
  22439. }
  22440. this.getTranformationMatrix();
  22441. if (!this._frustumPlanes) {
  22442. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22443. }
  22444. else {
  22445. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22446. }
  22447. this._refreshFrustumPlanes = false;
  22448. };
  22449. Camera.prototype.isInFrustum = function (target) {
  22450. this.updateFrustumPlanes();
  22451. return target.isInFrustum(this._frustumPlanes);
  22452. };
  22453. Camera.prototype.isCompletelyInFrustum = function (target) {
  22454. this.updateFrustumPlanes();
  22455. return target.isCompletelyInFrustum(this._frustumPlanes);
  22456. };
  22457. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22458. if (length === void 0) { length = 100; }
  22459. if (!transform) {
  22460. transform = this.getWorldMatrix();
  22461. }
  22462. if (!origin) {
  22463. origin = this.position;
  22464. }
  22465. var forward = new BABYLON.Vector3(0, 0, 1);
  22466. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22467. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22468. return new BABYLON.Ray(origin, direction, length);
  22469. };
  22470. /**
  22471. * Releases resources associated with this node.
  22472. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22473. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22474. */
  22475. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22476. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22477. // Observables
  22478. this.onViewMatrixChangedObservable.clear();
  22479. this.onProjectionMatrixChangedObservable.clear();
  22480. this.onAfterCheckInputsObservable.clear();
  22481. this.onRestoreStateObservable.clear();
  22482. // Inputs
  22483. if (this.inputs) {
  22484. this.inputs.clear();
  22485. }
  22486. // Animations
  22487. this.getScene().stopAnimation(this);
  22488. // Remove from scene
  22489. this.getScene().removeCamera(this);
  22490. while (this._rigCameras.length > 0) {
  22491. var camera = this._rigCameras.pop();
  22492. if (camera) {
  22493. camera.dispose();
  22494. }
  22495. }
  22496. // Postprocesses
  22497. if (this._rigPostProcess) {
  22498. this._rigPostProcess.dispose(this);
  22499. this._rigPostProcess = null;
  22500. this._postProcesses = [];
  22501. }
  22502. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22503. this._rigPostProcess = null;
  22504. this._postProcesses = [];
  22505. }
  22506. else {
  22507. var i = this._postProcesses.length;
  22508. while (--i >= 0) {
  22509. var postProcess = this._postProcesses[i];
  22510. if (postProcess) {
  22511. postProcess.dispose(this);
  22512. }
  22513. }
  22514. }
  22515. // Render targets
  22516. var i = this.customRenderTargets.length;
  22517. while (--i >= 0) {
  22518. this.customRenderTargets[i].dispose();
  22519. }
  22520. this.customRenderTargets = [];
  22521. // Active Meshes
  22522. this._activeMeshes.dispose();
  22523. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22524. };
  22525. Object.defineProperty(Camera.prototype, "leftCamera", {
  22526. // ---- Camera rigs section ----
  22527. get: function () {
  22528. if (this._rigCameras.length < 1) {
  22529. return null;
  22530. }
  22531. return this._rigCameras[0];
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. Object.defineProperty(Camera.prototype, "rightCamera", {
  22537. get: function () {
  22538. if (this._rigCameras.length < 2) {
  22539. return null;
  22540. }
  22541. return this._rigCameras[1];
  22542. },
  22543. enumerable: true,
  22544. configurable: true
  22545. });
  22546. Camera.prototype.getLeftTarget = function () {
  22547. if (this._rigCameras.length < 1) {
  22548. return null;
  22549. }
  22550. return this._rigCameras[0].getTarget();
  22551. };
  22552. Camera.prototype.getRightTarget = function () {
  22553. if (this._rigCameras.length < 2) {
  22554. return null;
  22555. }
  22556. return this._rigCameras[1].getTarget();
  22557. };
  22558. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22559. if (this.cameraRigMode === mode) {
  22560. return;
  22561. }
  22562. while (this._rigCameras.length > 0) {
  22563. var camera = this._rigCameras.pop();
  22564. if (camera) {
  22565. camera.dispose();
  22566. }
  22567. }
  22568. this.cameraRigMode = mode;
  22569. this._cameraRigParams = {};
  22570. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22571. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22572. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22573. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22574. // create the rig cameras, unless none
  22575. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22576. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22577. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22578. if (leftCamera && rightCamera) {
  22579. this._rigCameras.push(leftCamera);
  22580. this._rigCameras.push(rightCamera);
  22581. }
  22582. }
  22583. switch (this.cameraRigMode) {
  22584. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22585. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22586. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22587. break;
  22588. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22589. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22590. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22591. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22592. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22593. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22594. break;
  22595. case Camera.RIG_MODE_VR:
  22596. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22597. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22598. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22599. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22600. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22601. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22602. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22603. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22604. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22605. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22606. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22607. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22608. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22609. if (metrics.compensateDistortion) {
  22610. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22611. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22612. }
  22613. break;
  22614. case Camera.RIG_MODE_WEBVR:
  22615. if (rigParams.vrDisplay) {
  22616. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22617. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22618. //Left eye
  22619. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22620. this._rigCameras[0].setCameraRigParameter("left", true);
  22621. //leaving this for future reference
  22622. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22623. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22624. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22625. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22626. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22627. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22628. this._rigCameras[0].parent = this;
  22629. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22630. //Right eye
  22631. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22632. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22633. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22634. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22635. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22636. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22637. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22638. this._rigCameras[1].parent = this;
  22639. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22640. if (Camera.UseAlternateWebVRRendering) {
  22641. this._rigCameras[1]._skipRendering = true;
  22642. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22643. }
  22644. }
  22645. break;
  22646. }
  22647. this._cascadePostProcessesToRigCams();
  22648. this.update();
  22649. };
  22650. Camera.prototype._getVRProjectionMatrix = function () {
  22651. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22652. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22653. return this._projectionMatrix;
  22654. };
  22655. Camera.prototype._updateCameraRotationMatrix = function () {
  22656. //Here for WebVR
  22657. };
  22658. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22659. //Here for WebVR
  22660. };
  22661. /**
  22662. * This function MUST be overwritten by the different WebVR cameras available.
  22663. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22664. */
  22665. Camera.prototype._getWebVRProjectionMatrix = function () {
  22666. return BABYLON.Matrix.Identity();
  22667. };
  22668. /**
  22669. * This function MUST be overwritten by the different WebVR cameras available.
  22670. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22671. */
  22672. Camera.prototype._getWebVRViewMatrix = function () {
  22673. return BABYLON.Matrix.Identity();
  22674. };
  22675. Camera.prototype.setCameraRigParameter = function (name, value) {
  22676. if (!this._cameraRigParams) {
  22677. this._cameraRigParams = {};
  22678. }
  22679. this._cameraRigParams[name] = value;
  22680. //provisionnally:
  22681. if (name === "interaxialDistance") {
  22682. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22683. }
  22684. };
  22685. /**
  22686. * needs to be overridden by children so sub has required properties to be copied
  22687. */
  22688. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22689. return null;
  22690. };
  22691. /**
  22692. * May need to be overridden by children
  22693. */
  22694. Camera.prototype._updateRigCameras = function () {
  22695. for (var i = 0; i < this._rigCameras.length; i++) {
  22696. this._rigCameras[i].minZ = this.minZ;
  22697. this._rigCameras[i].maxZ = this.maxZ;
  22698. this._rigCameras[i].fov = this.fov;
  22699. }
  22700. // only update viewport when ANAGLYPH
  22701. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22702. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22703. }
  22704. };
  22705. Camera.prototype._setupInputs = function () {
  22706. };
  22707. Camera.prototype.serialize = function () {
  22708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22709. // Type
  22710. serializationObject.type = this.getClassName();
  22711. // Parent
  22712. if (this.parent) {
  22713. serializationObject.parentId = this.parent.id;
  22714. }
  22715. if (this.inputs) {
  22716. this.inputs.serialize(serializationObject);
  22717. }
  22718. // Animations
  22719. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22720. serializationObject.ranges = this.serializeAnimationRanges();
  22721. return serializationObject;
  22722. };
  22723. Camera.prototype.clone = function (name) {
  22724. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22725. };
  22726. Camera.prototype.getDirection = function (localAxis) {
  22727. var result = BABYLON.Vector3.Zero();
  22728. this.getDirectionToRef(localAxis, result);
  22729. return result;
  22730. };
  22731. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22732. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22733. };
  22734. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22735. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22736. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22737. switch (type) {
  22738. case "ArcRotateCamera":
  22739. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22740. case "DeviceOrientationCamera":
  22741. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22742. case "FollowCamera":
  22743. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22744. case "ArcFollowCamera":
  22745. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22746. case "GamepadCamera":
  22747. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22748. case "TouchCamera":
  22749. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22750. case "VirtualJoysticksCamera":
  22751. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22752. case "WebVRFreeCamera":
  22753. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22754. case "WebVRGamepadCamera":
  22755. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22756. case "VRDeviceOrientationFreeCamera":
  22757. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22758. case "VRDeviceOrientationGamepadCamera":
  22759. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22760. case "AnaglyphArcRotateCamera":
  22761. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22762. case "AnaglyphFreeCamera":
  22763. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22764. case "AnaglyphGamepadCamera":
  22765. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22766. case "AnaglyphUniversalCamera":
  22767. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22768. case "StereoscopicArcRotateCamera":
  22769. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22770. case "StereoscopicFreeCamera":
  22771. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22772. case "StereoscopicGamepadCamera":
  22773. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22774. case "StereoscopicUniversalCamera":
  22775. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22776. case "FreeCamera": // Forcing Universal here
  22777. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22778. default: // Universal Camera is the default value
  22779. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22780. }
  22781. };
  22782. Camera.prototype.computeWorldMatrix = function () {
  22783. return this.getWorldMatrix();
  22784. };
  22785. Camera.Parse = function (parsedCamera, scene) {
  22786. var type = parsedCamera.type;
  22787. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22788. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22789. // Parent
  22790. if (parsedCamera.parentId) {
  22791. camera._waitingParentId = parsedCamera.parentId;
  22792. }
  22793. //If camera has an input manager, let it parse inputs settings
  22794. if (camera.inputs) {
  22795. camera.inputs.parse(parsedCamera);
  22796. camera._setupInputs();
  22797. }
  22798. if (camera.setPosition) { // need to force position
  22799. camera.position.copyFromFloats(0, 0, 0);
  22800. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22801. }
  22802. // Target
  22803. if (parsedCamera.target) {
  22804. if (camera.setTarget) {
  22805. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22806. }
  22807. }
  22808. // Apply 3d rig, when found
  22809. if (parsedCamera.cameraRigMode) {
  22810. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22811. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22812. }
  22813. // Animations
  22814. if (parsedCamera.animations) {
  22815. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22816. var parsedAnimation = parsedCamera.animations[animationIndex];
  22817. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22818. }
  22819. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22820. }
  22821. if (parsedCamera.autoAnimate) {
  22822. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22823. }
  22824. return camera;
  22825. };
  22826. // Statics
  22827. Camera._PERSPECTIVE_CAMERA = 0;
  22828. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22829. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22830. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22831. Camera._RIG_MODE_NONE = 0;
  22832. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22833. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22834. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22835. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22836. Camera._RIG_MODE_VR = 20;
  22837. Camera._RIG_MODE_WEBVR = 21;
  22838. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22839. Camera.UseAlternateWebVRRendering = false;
  22840. __decorate([
  22841. BABYLON.serializeAsVector3()
  22842. ], Camera.prototype, "position", void 0);
  22843. __decorate([
  22844. BABYLON.serializeAsVector3()
  22845. ], Camera.prototype, "upVector", void 0);
  22846. __decorate([
  22847. BABYLON.serialize()
  22848. ], Camera.prototype, "orthoLeft", void 0);
  22849. __decorate([
  22850. BABYLON.serialize()
  22851. ], Camera.prototype, "orthoRight", void 0);
  22852. __decorate([
  22853. BABYLON.serialize()
  22854. ], Camera.prototype, "orthoBottom", void 0);
  22855. __decorate([
  22856. BABYLON.serialize()
  22857. ], Camera.prototype, "orthoTop", void 0);
  22858. __decorate([
  22859. BABYLON.serialize()
  22860. ], Camera.prototype, "fov", void 0);
  22861. __decorate([
  22862. BABYLON.serialize()
  22863. ], Camera.prototype, "minZ", void 0);
  22864. __decorate([
  22865. BABYLON.serialize()
  22866. ], Camera.prototype, "maxZ", void 0);
  22867. __decorate([
  22868. BABYLON.serialize()
  22869. ], Camera.prototype, "inertia", void 0);
  22870. __decorate([
  22871. BABYLON.serialize()
  22872. ], Camera.prototype, "mode", void 0);
  22873. __decorate([
  22874. BABYLON.serialize()
  22875. ], Camera.prototype, "layerMask", void 0);
  22876. __decorate([
  22877. BABYLON.serialize()
  22878. ], Camera.prototype, "fovMode", void 0);
  22879. __decorate([
  22880. BABYLON.serialize()
  22881. ], Camera.prototype, "cameraRigMode", void 0);
  22882. __decorate([
  22883. BABYLON.serialize()
  22884. ], Camera.prototype, "interaxialDistance", void 0);
  22885. __decorate([
  22886. BABYLON.serialize()
  22887. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22888. return Camera;
  22889. }(BABYLON.Node));
  22890. BABYLON.Camera = Camera;
  22891. })(BABYLON || (BABYLON = {}));
  22892. //# sourceMappingURL=babylon.camera.js.map
  22893. var BABYLON;
  22894. (function (BABYLON) {
  22895. var RenderingManager = /** @class */ (function () {
  22896. function RenderingManager(scene) {
  22897. this._renderingGroups = new Array();
  22898. this._autoClearDepthStencil = {};
  22899. this._customOpaqueSortCompareFn = {};
  22900. this._customAlphaTestSortCompareFn = {};
  22901. this._customTransparentSortCompareFn = {};
  22902. this._renderinGroupInfo = null;
  22903. this._scene = scene;
  22904. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22905. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22906. }
  22907. }
  22908. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22909. if (depth === void 0) { depth = true; }
  22910. if (stencil === void 0) { stencil = true; }
  22911. if (this._depthStencilBufferAlreadyCleaned) {
  22912. return;
  22913. }
  22914. this._scene.getEngine().clear(null, false, depth, stencil);
  22915. this._depthStencilBufferAlreadyCleaned = true;
  22916. };
  22917. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22918. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22919. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22920. var info = null;
  22921. if (observable) {
  22922. if (!this._renderinGroupInfo) {
  22923. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22924. }
  22925. info = this._renderinGroupInfo;
  22926. info.scene = this._scene;
  22927. info.camera = this._scene.activeCamera;
  22928. }
  22929. // Dispatch sprites
  22930. if (renderSprites) {
  22931. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22932. var manager = this._scene.spriteManagers[index];
  22933. this.dispatchSprites(manager);
  22934. }
  22935. }
  22936. // Render
  22937. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22938. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22939. var renderingGroup = this._renderingGroups[index];
  22940. if (!renderingGroup && !observable)
  22941. continue;
  22942. var renderingGroupMask = 0;
  22943. // Fire PRECLEAR stage
  22944. if (observable && info) {
  22945. renderingGroupMask = Math.pow(2, index);
  22946. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22947. info.renderingGroupId = index;
  22948. observable.notifyObservers(info, renderingGroupMask);
  22949. }
  22950. // Clear depth/stencil if needed
  22951. if (RenderingManager.AUTOCLEAR) {
  22952. var autoClear = this._autoClearDepthStencil[index];
  22953. if (autoClear && autoClear.autoClear) {
  22954. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22955. }
  22956. }
  22957. if (observable && info) {
  22958. // Fire PREOPAQUE stage
  22959. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22960. observable.notifyObservers(info, renderingGroupMask);
  22961. // Fire PRETRANSPARENT stage
  22962. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22963. observable.notifyObservers(info, renderingGroupMask);
  22964. }
  22965. if (renderingGroup)
  22966. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22967. // Fire POSTTRANSPARENT stage
  22968. if (observable && info) {
  22969. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22970. observable.notifyObservers(info, renderingGroupMask);
  22971. }
  22972. }
  22973. };
  22974. RenderingManager.prototype.reset = function () {
  22975. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22976. var renderingGroup = this._renderingGroups[index];
  22977. if (renderingGroup) {
  22978. renderingGroup.prepare();
  22979. }
  22980. }
  22981. };
  22982. RenderingManager.prototype.dispose = function () {
  22983. this.freeRenderingGroups();
  22984. this._renderingGroups.length = 0;
  22985. };
  22986. /**
  22987. * Clear the info related to rendering groups preventing retention points during dispose.
  22988. */
  22989. RenderingManager.prototype.freeRenderingGroups = function () {
  22990. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22991. var renderingGroup = this._renderingGroups[index];
  22992. if (renderingGroup) {
  22993. renderingGroup.dispose();
  22994. }
  22995. }
  22996. };
  22997. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22998. if (this._renderingGroups[renderingGroupId] === undefined) {
  22999. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23000. }
  23001. };
  23002. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23003. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23004. this._prepareRenderingGroup(renderingGroupId);
  23005. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23006. };
  23007. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23008. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23009. this._prepareRenderingGroup(renderingGroupId);
  23010. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23011. };
  23012. /**
  23013. * @param subMesh The submesh to dispatch
  23014. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23015. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23016. */
  23017. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23018. if (mesh === undefined) {
  23019. mesh = subMesh.getMesh();
  23020. }
  23021. var renderingGroupId = mesh.renderingGroupId || 0;
  23022. this._prepareRenderingGroup(renderingGroupId);
  23023. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23024. };
  23025. /**
  23026. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23027. * This allowed control for front to back rendering or reversly depending of the special needs.
  23028. *
  23029. * @param renderingGroupId The rendering group id corresponding to its index
  23030. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23031. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23032. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23033. */
  23034. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23035. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23036. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23037. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23038. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23039. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23040. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23041. if (this._renderingGroups[renderingGroupId]) {
  23042. var group = this._renderingGroups[renderingGroupId];
  23043. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23044. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23045. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23046. }
  23047. };
  23048. /**
  23049. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23050. *
  23051. * @param renderingGroupId The rendering group id corresponding to its index
  23052. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23053. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23054. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23055. */
  23056. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23057. if (depth === void 0) { depth = true; }
  23058. if (stencil === void 0) { stencil = true; }
  23059. this._autoClearDepthStencil[renderingGroupId] = {
  23060. autoClear: autoClearDepthStencil,
  23061. depth: depth,
  23062. stencil: stencil
  23063. };
  23064. };
  23065. /**
  23066. * The max id used for rendering groups (not included)
  23067. */
  23068. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23069. /**
  23070. * The min id used for rendering groups (included)
  23071. */
  23072. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23073. /**
  23074. * Used to globally prevent autoclearing scenes.
  23075. */
  23076. RenderingManager.AUTOCLEAR = true;
  23077. return RenderingManager;
  23078. }());
  23079. BABYLON.RenderingManager = RenderingManager;
  23080. })(BABYLON || (BABYLON = {}));
  23081. //# sourceMappingURL=babylon.renderingManager.js.map
  23082. var BABYLON;
  23083. (function (BABYLON) {
  23084. var RenderingGroup = /** @class */ (function () {
  23085. /**
  23086. * Creates a new rendering group.
  23087. * @param index The rendering group index
  23088. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23089. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23090. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23091. */
  23092. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23093. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23094. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23095. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23096. this.index = index;
  23097. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23098. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23099. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23100. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23101. this._particleSystems = new BABYLON.SmartArray(256);
  23102. this._spriteManagers = new BABYLON.SmartArray(256);
  23103. this._edgesRenderers = new BABYLON.SmartArray(16);
  23104. this._scene = scene;
  23105. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23106. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23107. this.transparentSortCompareFn = transparentSortCompareFn;
  23108. }
  23109. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23110. /**
  23111. * Set the opaque sort comparison function.
  23112. * If null the sub meshes will be render in the order they were created
  23113. */
  23114. set: function (value) {
  23115. this._opaqueSortCompareFn = value;
  23116. if (value) {
  23117. this._renderOpaque = this.renderOpaqueSorted;
  23118. }
  23119. else {
  23120. this._renderOpaque = RenderingGroup.renderUnsorted;
  23121. }
  23122. },
  23123. enumerable: true,
  23124. configurable: true
  23125. });
  23126. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23127. /**
  23128. * Set the alpha test sort comparison function.
  23129. * If null the sub meshes will be render in the order they were created
  23130. */
  23131. set: function (value) {
  23132. this._alphaTestSortCompareFn = value;
  23133. if (value) {
  23134. this._renderAlphaTest = this.renderAlphaTestSorted;
  23135. }
  23136. else {
  23137. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23138. }
  23139. },
  23140. enumerable: true,
  23141. configurable: true
  23142. });
  23143. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23144. /**
  23145. * Set the transparent sort comparison function.
  23146. * If null the sub meshes will be render in the order they were created
  23147. */
  23148. set: function (value) {
  23149. if (value) {
  23150. this._transparentSortCompareFn = value;
  23151. }
  23152. else {
  23153. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23154. }
  23155. this._renderTransparent = this.renderTransparentSorted;
  23156. },
  23157. enumerable: true,
  23158. configurable: true
  23159. });
  23160. /**
  23161. * Render all the sub meshes contained in the group.
  23162. * @param customRenderFunction Used to override the default render behaviour of the group.
  23163. * @returns true if rendered some submeshes.
  23164. */
  23165. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23166. if (customRenderFunction) {
  23167. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23168. return;
  23169. }
  23170. var engine = this._scene.getEngine();
  23171. // Depth only
  23172. if (this._depthOnlySubMeshes.length !== 0) {
  23173. engine.setColorWrite(false);
  23174. this._renderAlphaTest(this._depthOnlySubMeshes);
  23175. engine.setColorWrite(true);
  23176. }
  23177. // Opaque
  23178. if (this._opaqueSubMeshes.length !== 0) {
  23179. this._renderOpaque(this._opaqueSubMeshes);
  23180. }
  23181. // Alpha test
  23182. if (this._alphaTestSubMeshes.length !== 0) {
  23183. this._renderAlphaTest(this._alphaTestSubMeshes);
  23184. }
  23185. var stencilState = engine.getStencilBuffer();
  23186. engine.setStencilBuffer(false);
  23187. // Sprites
  23188. if (renderSprites) {
  23189. this._renderSprites();
  23190. }
  23191. // Particles
  23192. if (renderParticles) {
  23193. this._renderParticles(activeMeshes);
  23194. }
  23195. if (this.onBeforeTransparentRendering) {
  23196. this.onBeforeTransparentRendering();
  23197. }
  23198. // Transparent
  23199. if (this._transparentSubMeshes.length !== 0) {
  23200. this._renderTransparent(this._transparentSubMeshes);
  23201. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23202. }
  23203. // Set back stencil to false in case it changes before the edge renderer.
  23204. engine.setStencilBuffer(false);
  23205. // Edges
  23206. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23207. this._edgesRenderers.data[edgesRendererIndex].render();
  23208. }
  23209. // Restore Stencil state.
  23210. engine.setStencilBuffer(stencilState);
  23211. };
  23212. /**
  23213. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23214. * @param subMeshes The submeshes to render
  23215. */
  23216. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23217. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23218. };
  23219. /**
  23220. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23221. * @param subMeshes The submeshes to render
  23222. */
  23223. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23224. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23225. };
  23226. /**
  23227. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23228. * @param subMeshes The submeshes to render
  23229. */
  23230. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23231. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23232. };
  23233. /**
  23234. * Renders the submeshes in a specified order.
  23235. * @param subMeshes The submeshes to sort before render
  23236. * @param sortCompareFn The comparison function use to sort
  23237. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23238. * @param transparent Specifies to activate blending if true
  23239. */
  23240. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23241. var subIndex = 0;
  23242. var subMesh;
  23243. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23244. for (; subIndex < subMeshes.length; subIndex++) {
  23245. subMesh = subMeshes.data[subIndex];
  23246. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23247. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23248. }
  23249. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23250. if (sortCompareFn) {
  23251. sortedArray.sort(sortCompareFn);
  23252. }
  23253. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23254. subMesh = sortedArray[subIndex];
  23255. if (transparent) {
  23256. var material = subMesh.getMaterial();
  23257. if (material && material.needDepthPrePass) {
  23258. var engine = material.getScene().getEngine();
  23259. engine.setColorWrite(false);
  23260. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23261. subMesh.render(false);
  23262. engine.setColorWrite(true);
  23263. }
  23264. }
  23265. subMesh.render(transparent);
  23266. }
  23267. };
  23268. /**
  23269. * Renders the submeshes in the order they were dispatched (no sort applied).
  23270. * @param subMeshes The submeshes to render
  23271. */
  23272. RenderingGroup.renderUnsorted = function (subMeshes) {
  23273. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23274. var submesh = subMeshes.data[subIndex];
  23275. submesh.render(false);
  23276. }
  23277. };
  23278. /**
  23279. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23280. * are rendered back to front if in the same alpha index.
  23281. *
  23282. * @param a The first submesh
  23283. * @param b The second submesh
  23284. * @returns The result of the comparison
  23285. */
  23286. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23287. // Alpha index first
  23288. if (a._alphaIndex > b._alphaIndex) {
  23289. return 1;
  23290. }
  23291. if (a._alphaIndex < b._alphaIndex) {
  23292. return -1;
  23293. }
  23294. // Then distance to camera
  23295. return RenderingGroup.backToFrontSortCompare(a, b);
  23296. };
  23297. /**
  23298. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23299. * are rendered back to front.
  23300. *
  23301. * @param a The first submesh
  23302. * @param b The second submesh
  23303. * @returns The result of the comparison
  23304. */
  23305. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23306. // Then distance to camera
  23307. if (a._distanceToCamera < b._distanceToCamera) {
  23308. return 1;
  23309. }
  23310. if (a._distanceToCamera > b._distanceToCamera) {
  23311. return -1;
  23312. }
  23313. return 0;
  23314. };
  23315. /**
  23316. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23317. * are rendered front to back (prevent overdraw).
  23318. *
  23319. * @param a The first submesh
  23320. * @param b The second submesh
  23321. * @returns The result of the comparison
  23322. */
  23323. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23324. // Then distance to camera
  23325. if (a._distanceToCamera < b._distanceToCamera) {
  23326. return -1;
  23327. }
  23328. if (a._distanceToCamera > b._distanceToCamera) {
  23329. return 1;
  23330. }
  23331. return 0;
  23332. };
  23333. /**
  23334. * Resets the different lists of submeshes to prepare a new frame.
  23335. */
  23336. RenderingGroup.prototype.prepare = function () {
  23337. this._opaqueSubMeshes.reset();
  23338. this._transparentSubMeshes.reset();
  23339. this._alphaTestSubMeshes.reset();
  23340. this._depthOnlySubMeshes.reset();
  23341. this._particleSystems.reset();
  23342. this._spriteManagers.reset();
  23343. this._edgesRenderers.reset();
  23344. };
  23345. RenderingGroup.prototype.dispose = function () {
  23346. this._opaqueSubMeshes.dispose();
  23347. this._transparentSubMeshes.dispose();
  23348. this._alphaTestSubMeshes.dispose();
  23349. this._depthOnlySubMeshes.dispose();
  23350. this._particleSystems.dispose();
  23351. this._spriteManagers.dispose();
  23352. this._edgesRenderers.dispose();
  23353. };
  23354. /**
  23355. * Inserts the submesh in its correct queue depending on its material.
  23356. * @param subMesh The submesh to dispatch
  23357. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23358. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23359. */
  23360. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23361. // Get mesh and materials if not provided
  23362. if (mesh === undefined) {
  23363. mesh = subMesh.getMesh();
  23364. }
  23365. if (material === undefined) {
  23366. material = subMesh.getMaterial();
  23367. }
  23368. if (material === null || material === undefined) {
  23369. return;
  23370. }
  23371. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23372. this._transparentSubMeshes.push(subMesh);
  23373. }
  23374. else if (material.needAlphaTesting()) { // Alpha test
  23375. if (material.needDepthPrePass) {
  23376. this._depthOnlySubMeshes.push(subMesh);
  23377. }
  23378. this._alphaTestSubMeshes.push(subMesh);
  23379. }
  23380. else {
  23381. if (material.needDepthPrePass) {
  23382. this._depthOnlySubMeshes.push(subMesh);
  23383. }
  23384. this._opaqueSubMeshes.push(subMesh); // Opaque
  23385. }
  23386. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23387. this._edgesRenderers.push(mesh._edgesRenderer);
  23388. }
  23389. };
  23390. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23391. this._spriteManagers.push(spriteManager);
  23392. };
  23393. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23394. this._particleSystems.push(particleSystem);
  23395. };
  23396. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23397. if (this._particleSystems.length === 0) {
  23398. return;
  23399. }
  23400. // Particles
  23401. var activeCamera = this._scene.activeCamera;
  23402. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23403. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23404. var particleSystem = this._particleSystems.data[particleIndex];
  23405. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23406. continue;
  23407. }
  23408. var emitter = particleSystem.emitter;
  23409. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23410. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23411. }
  23412. }
  23413. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23414. };
  23415. RenderingGroup.prototype._renderSprites = function () {
  23416. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23417. return;
  23418. }
  23419. // Sprites
  23420. var activeCamera = this._scene.activeCamera;
  23421. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23422. for (var id = 0; id < this._spriteManagers.length; id++) {
  23423. var spriteManager = this._spriteManagers.data[id];
  23424. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23425. spriteManager.render();
  23426. }
  23427. }
  23428. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23429. };
  23430. return RenderingGroup;
  23431. }());
  23432. BABYLON.RenderingGroup = RenderingGroup;
  23433. })(BABYLON || (BABYLON = {}));
  23434. //# sourceMappingURL=babylon.renderingGroup.js.map
  23435. var BABYLON;
  23436. (function (BABYLON) {
  23437. /** @hidden */
  23438. var ClickInfo = /** @class */ (function () {
  23439. function ClickInfo() {
  23440. this._singleClick = false;
  23441. this._doubleClick = false;
  23442. this._hasSwiped = false;
  23443. this._ignore = false;
  23444. }
  23445. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23446. get: function () {
  23447. return this._singleClick;
  23448. },
  23449. set: function (b) {
  23450. this._singleClick = b;
  23451. },
  23452. enumerable: true,
  23453. configurable: true
  23454. });
  23455. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23456. get: function () {
  23457. return this._doubleClick;
  23458. },
  23459. set: function (b) {
  23460. this._doubleClick = b;
  23461. },
  23462. enumerable: true,
  23463. configurable: true
  23464. });
  23465. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23466. get: function () {
  23467. return this._hasSwiped;
  23468. },
  23469. set: function (b) {
  23470. this._hasSwiped = b;
  23471. },
  23472. enumerable: true,
  23473. configurable: true
  23474. });
  23475. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23476. get: function () {
  23477. return this._ignore;
  23478. },
  23479. set: function (b) {
  23480. this._ignore = b;
  23481. },
  23482. enumerable: true,
  23483. configurable: true
  23484. });
  23485. return ClickInfo;
  23486. }());
  23487. /**
  23488. * This class is used by the onRenderingGroupObservable
  23489. */
  23490. var RenderingGroupInfo = /** @class */ (function () {
  23491. function RenderingGroupInfo() {
  23492. }
  23493. /**
  23494. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23495. * This stage will be fired no matter what
  23496. */
  23497. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23498. /**
  23499. * Called before opaque object are rendered.
  23500. * This stage will be fired only if there's 3D Opaque content to render
  23501. */
  23502. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23503. /**
  23504. * Called after the opaque objects are rendered and before the transparent ones
  23505. * This stage will be fired only if there's 3D transparent content to render
  23506. */
  23507. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23508. /**
  23509. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23510. * This stage will be fired no matter what
  23511. */
  23512. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23513. return RenderingGroupInfo;
  23514. }());
  23515. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23516. /**
  23517. * Represents a scene to be rendered by the engine.
  23518. * @see http://doc.babylonjs.com/features/scene
  23519. */
  23520. var Scene = /** @class */ (function () {
  23521. /**
  23522. * Creates a new Scene
  23523. * @param engine defines the engine to use to render this scene
  23524. */
  23525. function Scene(engine) {
  23526. // Members
  23527. /**
  23528. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23529. */
  23530. this.autoClear = true;
  23531. /**
  23532. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23533. */
  23534. this.autoClearDepthAndStencil = true;
  23535. /**
  23536. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23537. */
  23538. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23539. /**
  23540. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23541. */
  23542. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23543. this._forceWireframe = false;
  23544. this._forcePointsCloud = false;
  23545. /**
  23546. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23547. */
  23548. this.forceShowBoundingBoxes = false;
  23549. /**
  23550. * Gets or sets a boolean indicating if animations are enabled
  23551. */
  23552. this.animationsEnabled = true;
  23553. this._animationPropertiesOverride = null;
  23554. /**
  23555. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23556. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23557. */
  23558. this.useConstantAnimationDeltaTime = false;
  23559. /**
  23560. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23561. * Please note that it requires to run a ray cast through the scene on every frame
  23562. */
  23563. this.constantlyUpdateMeshUnderPointer = false;
  23564. /**
  23565. * Defines the HTML cursor to use when hovering over interactive elements
  23566. */
  23567. this.hoverCursor = "pointer";
  23568. /**
  23569. * Defines the HTML default cursor to use (empty by default)
  23570. */
  23571. this.defaultCursor = "";
  23572. /**
  23573. * This is used to call preventDefault() on pointer down
  23574. * in order to block unwanted artifacts like system double clicks
  23575. */
  23576. this.preventDefaultOnPointerDown = true;
  23577. // Metadata
  23578. /**
  23579. * Gets or sets user defined metadata
  23580. */
  23581. this.metadata = null;
  23582. /**
  23583. * Use this array to add regular expressions used to disable offline support for specific urls
  23584. */
  23585. this.disableOfflineSupportExceptionRules = new Array();
  23586. /**
  23587. * An event triggered when the scene is disposed.
  23588. */
  23589. this.onDisposeObservable = new BABYLON.Observable();
  23590. this._onDisposeObserver = null;
  23591. /**
  23592. * An event triggered before rendering the scene (right after animations and physics)
  23593. */
  23594. this.onBeforeRenderObservable = new BABYLON.Observable();
  23595. this._onBeforeRenderObserver = null;
  23596. /**
  23597. * An event triggered after rendering the scene
  23598. */
  23599. this.onAfterRenderObservable = new BABYLON.Observable();
  23600. this._onAfterRenderObserver = null;
  23601. /**
  23602. * An event triggered before animating the scene
  23603. */
  23604. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23605. /**
  23606. * An event triggered after animations processing
  23607. */
  23608. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23609. /**
  23610. * An event triggered before draw calls are ready to be sent
  23611. */
  23612. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23613. /**
  23614. * An event triggered after draw calls have been sent
  23615. */
  23616. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23617. /**
  23618. * An event triggered when physic simulation is about to be run
  23619. */
  23620. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23621. /**
  23622. * An event triggered when physic simulation has been done
  23623. */
  23624. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23625. /**
  23626. * An event triggered when the scene is ready
  23627. */
  23628. this.onReadyObservable = new BABYLON.Observable();
  23629. /**
  23630. * An event triggered before rendering a camera
  23631. */
  23632. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23633. this._onBeforeCameraRenderObserver = null;
  23634. /**
  23635. * An event triggered after rendering a camera
  23636. */
  23637. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23638. this._onAfterCameraRenderObserver = null;
  23639. /**
  23640. * An event triggered when active meshes evaluation is about to start
  23641. */
  23642. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23643. /**
  23644. * An event triggered when active meshes evaluation is done
  23645. */
  23646. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23647. /**
  23648. * An event triggered when particles rendering is about to start
  23649. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23650. */
  23651. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23652. /**
  23653. * An event triggered when particles rendering is done
  23654. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23655. */
  23656. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23657. /**
  23658. * An event triggered when sprites rendering is about to start
  23659. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23660. */
  23661. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23662. /**
  23663. * An event triggered when sprites rendering is done
  23664. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23665. */
  23666. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23667. /**
  23668. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23669. */
  23670. this.onDataLoadedObservable = new BABYLON.Observable();
  23671. /**
  23672. * An event triggered when a camera is created
  23673. */
  23674. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23675. /**
  23676. * An event triggered when a camera is removed
  23677. */
  23678. this.onCameraRemovedObservable = new BABYLON.Observable();
  23679. /**
  23680. * An event triggered when a light is created
  23681. */
  23682. this.onNewLightAddedObservable = new BABYLON.Observable();
  23683. /**
  23684. * An event triggered when a light is removed
  23685. */
  23686. this.onLightRemovedObservable = new BABYLON.Observable();
  23687. /**
  23688. * An event triggered when a geometry is created
  23689. */
  23690. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23691. /**
  23692. * An event triggered when a geometry is removed
  23693. */
  23694. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23695. /**
  23696. * An event triggered when a transform node is created
  23697. */
  23698. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23699. /**
  23700. * An event triggered when a transform node is removed
  23701. */
  23702. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23703. /**
  23704. * An event triggered when a mesh is created
  23705. */
  23706. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered when a mesh is removed
  23709. */
  23710. this.onMeshRemovedObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered when render targets are about to be rendered
  23713. * Can happen multiple times per frame.
  23714. */
  23715. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23716. /**
  23717. * An event triggered when render targets were rendered.
  23718. * Can happen multiple times per frame.
  23719. */
  23720. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23721. /**
  23722. * An event triggered before calculating deterministic simulation step
  23723. */
  23724. this.onBeforeStepObservable = new BABYLON.Observable();
  23725. /**
  23726. * An event triggered after calculating deterministic simulation step
  23727. */
  23728. this.onAfterStepObservable = new BABYLON.Observable();
  23729. /**
  23730. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23731. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23732. * 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)
  23733. */
  23734. this.onRenderingGroupObservable = new BABYLON.Observable();
  23735. // Animations
  23736. /**
  23737. * Gets a list of Animations associated with the scene
  23738. */
  23739. this.animations = [];
  23740. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23741. /**
  23742. * 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).
  23743. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23744. */
  23745. this.onPrePointerObservable = new BABYLON.Observable();
  23746. /**
  23747. * Observable event triggered each time an input event is received from the rendering canvas
  23748. */
  23749. this.onPointerObservable = new BABYLON.Observable();
  23750. this._meshPickProceed = false;
  23751. this._currentPickResult = null;
  23752. this._previousPickResult = null;
  23753. this._totalPointersPressed = 0;
  23754. this._doubleClickOccured = false;
  23755. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23756. this.cameraToUseForPointers = null;
  23757. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23758. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23759. this._startingPointerTime = 0;
  23760. this._previousStartingPointerTime = 0;
  23761. this._pointerCaptures = {};
  23762. // Deterministic lockstep
  23763. this._timeAccumulator = 0;
  23764. this._currentStepId = 0;
  23765. this._currentInternalStep = 0;
  23766. // Keyboard
  23767. /**
  23768. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23769. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23770. */
  23771. this.onPreKeyboardObservable = new BABYLON.Observable();
  23772. /**
  23773. * Observable event triggered each time an keyboard event is received from the hosting window
  23774. */
  23775. this.onKeyboardObservable = new BABYLON.Observable();
  23776. // Coordinates system
  23777. this._useRightHandedSystem = false;
  23778. // Fog
  23779. this._fogEnabled = true;
  23780. this._fogMode = Scene.FOGMODE_NONE;
  23781. /**
  23782. * Gets or sets the fog color to use
  23783. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23784. */
  23785. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23786. /**
  23787. * Gets or sets the fog density to use
  23788. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23789. */
  23790. this.fogDensity = 0.1;
  23791. /**
  23792. * Gets or sets the fog start distance to use
  23793. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23794. */
  23795. this.fogStart = 0;
  23796. /**
  23797. * Gets or sets the fog end distance to use
  23798. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23799. */
  23800. this.fogEnd = 1000.0;
  23801. // Lights
  23802. this._shadowsEnabled = true;
  23803. this._lightsEnabled = true;
  23804. /**
  23805. * All of the lights added to this scene
  23806. * @see http://doc.babylonjs.com/babylon101/lights
  23807. */
  23808. this.lights = new Array();
  23809. // Cameras
  23810. /** All of the cameras added to this scene.
  23811. * @see http://doc.babylonjs.com/babylon101/cameras
  23812. */
  23813. this.cameras = new Array();
  23814. /** All of the active cameras added to this scene. */
  23815. this.activeCameras = new Array();
  23816. // Meshes
  23817. /**
  23818. * All of the tranform nodes added to this scene
  23819. * @see http://doc.babylonjs.com/how_to/transformnode
  23820. */
  23821. this.transformNodes = new Array();
  23822. /**
  23823. * All of the (abstract) meshes added to this scene
  23824. */
  23825. this.meshes = new Array();
  23826. /**
  23827. * All of the animation groups added to this scene
  23828. * @see http://doc.babylonjs.com/how_to/group
  23829. */
  23830. this.animationGroups = new Array();
  23831. // Geometries
  23832. this._geometries = new Array();
  23833. /**
  23834. * All of the materials added to this scene
  23835. * @see http://doc.babylonjs.com/babylon101/materials
  23836. */
  23837. this.materials = new Array();
  23838. /**
  23839. * All of the multi-materials added to this scene
  23840. * @see http://doc.babylonjs.com/how_to/multi_materials
  23841. */
  23842. this.multiMaterials = new Array();
  23843. // Textures
  23844. this._texturesEnabled = true;
  23845. /**
  23846. * All of the textures added to this scene
  23847. */
  23848. this.textures = new Array();
  23849. // Particles
  23850. /**
  23851. * Gets or sets a boolean indicating if particles are enabled on this scene
  23852. */
  23853. this.particlesEnabled = true;
  23854. /**
  23855. * All of the particle systems added to this scene
  23856. * @see http://doc.babylonjs.com/babylon101/particles
  23857. */
  23858. this.particleSystems = new Array();
  23859. // Sprites
  23860. /**
  23861. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23862. */
  23863. this.spritesEnabled = true;
  23864. /**
  23865. * All of the sprite managers added to this scene
  23866. * @see http://doc.babylonjs.com/babylon101/sprites
  23867. */
  23868. this.spriteManagers = new Array();
  23869. /**
  23870. * The list of layers (background and foreground) of the scene
  23871. */
  23872. this.layers = new Array();
  23873. /**
  23874. * The list of effect layers (highlights/glow) added to the scene
  23875. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23876. * @see http://doc.babylonjs.com/how_to/glow_layer
  23877. */
  23878. this.effectLayers = new Array();
  23879. // Skeletons
  23880. this._skeletonsEnabled = true;
  23881. /**
  23882. * The list of skeletons added to the scene
  23883. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23884. */
  23885. this.skeletons = new Array();
  23886. // Morph targets
  23887. /**
  23888. * The list of morph target managers added to the scene
  23889. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23890. */
  23891. this.morphTargetManagers = new Array();
  23892. // Lens flares
  23893. /**
  23894. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23895. */
  23896. this.lensFlaresEnabled = true;
  23897. /**
  23898. * The list of lens flare system added to the scene
  23899. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23900. */
  23901. this.lensFlareSystems = new Array();
  23902. // Collisions
  23903. /**
  23904. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23905. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23906. */
  23907. this.collisionsEnabled = true;
  23908. /**
  23909. * Defines the gravity applied to this scene (used only for collisions)
  23910. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23911. */
  23912. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23913. // Postprocesses
  23914. /**
  23915. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23916. */
  23917. this.postProcessesEnabled = true;
  23918. /**
  23919. * The list of postprocesses added to the scene
  23920. */
  23921. this.postProcesses = new Array();
  23922. // Customs render targets
  23923. /**
  23924. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23925. */
  23926. this.renderTargetsEnabled = true;
  23927. /**
  23928. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23929. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23930. */
  23931. this.dumpNextRenderTargets = false;
  23932. /**
  23933. * The list of user defined render targets added to the scene
  23934. */
  23935. this.customRenderTargets = new Array();
  23936. /**
  23937. * Gets the list of meshes imported to the scene through SceneLoader
  23938. */
  23939. this.importedMeshesFiles = new Array();
  23940. // Probes
  23941. /**
  23942. * Gets or sets a boolean indicating if probes are enabled on this scene
  23943. */
  23944. this.probesEnabled = true;
  23945. /**
  23946. * The list of reflection probes added to the scene
  23947. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23948. */
  23949. this.reflectionProbes = new Array();
  23950. /** @hidden */
  23951. this._actionManagers = new Array();
  23952. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23953. // Procedural textures
  23954. /**
  23955. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23956. */
  23957. this.proceduralTexturesEnabled = true;
  23958. /**
  23959. * The list of procedural textures added to the scene
  23960. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23961. */
  23962. this.proceduralTextures = new Array();
  23963. /**
  23964. * The list of sound tracks added to the scene
  23965. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23966. */
  23967. this.soundTracks = new Array();
  23968. this._audioEnabled = true;
  23969. this._headphone = false;
  23970. // Performance counters
  23971. this._totalVertices = new BABYLON.PerfCounter();
  23972. /** @hidden */
  23973. this._activeIndices = new BABYLON.PerfCounter();
  23974. /** @hidden */
  23975. this._activeParticles = new BABYLON.PerfCounter();
  23976. /** @hidden */
  23977. this._activeBones = new BABYLON.PerfCounter();
  23978. this._animationTime = 0;
  23979. /**
  23980. * Gets or sets a general scale for animation speed
  23981. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23982. */
  23983. this.animationTimeScale = 1;
  23984. this._renderId = 0;
  23985. this._executeWhenReadyTimeoutId = -1;
  23986. this._intermediateRendering = false;
  23987. this._viewUpdateFlag = -1;
  23988. this._projectionUpdateFlag = -1;
  23989. this._alternateViewUpdateFlag = -1;
  23990. this._alternateProjectionUpdateFlag = -1;
  23991. /** @hidden */
  23992. this._toBeDisposed = new BABYLON.SmartArray(256);
  23993. this._activeRequests = new Array();
  23994. this._pendingData = new Array();
  23995. this._isDisposed = false;
  23996. /**
  23997. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23998. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23999. */
  24000. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24001. this._activeMeshes = new BABYLON.SmartArray(256);
  24002. this._processedMaterials = new BABYLON.SmartArray(256);
  24003. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24004. /** @hidden */
  24005. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24006. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24007. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24008. /** @hidden */
  24009. this._activeAnimatables = new Array();
  24010. this._transformMatrix = BABYLON.Matrix.Zero();
  24011. this._useAlternateCameraConfiguration = false;
  24012. this._alternateRendering = false;
  24013. /**
  24014. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24015. * This is useful if there are more lights that the maximum simulteanous authorized
  24016. */
  24017. this.requireLightSorting = false;
  24018. this._depthRenderer = {};
  24019. this._activeMeshesFrozen = false;
  24020. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24021. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24022. this._engine.scenes.push(this);
  24023. this._uid = null;
  24024. this._renderingManager = new BABYLON.RenderingManager(this);
  24025. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24026. if (BABYLON.OutlineRenderer) {
  24027. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24028. }
  24029. if (BABYLON.Tools.IsWindowObjectExist()) {
  24030. this.attachControl();
  24031. }
  24032. //simplification queue
  24033. if (BABYLON.SimplificationQueue) {
  24034. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24035. }
  24036. //collision coordinator initialization. For now legacy per default.
  24037. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24038. // Uniform Buffer
  24039. this._createUbo();
  24040. // Default Image processing definition.
  24041. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24042. }
  24043. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24044. /** The fog is deactivated */
  24045. get: function () {
  24046. return Scene._FOGMODE_NONE;
  24047. },
  24048. enumerable: true,
  24049. configurable: true
  24050. });
  24051. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24052. /** The fog density is following an exponential function */
  24053. get: function () {
  24054. return Scene._FOGMODE_EXP;
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24060. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24061. get: function () {
  24062. return Scene._FOGMODE_EXP2;
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24068. /** The fog density is following a linear function. */
  24069. get: function () {
  24070. return Scene._FOGMODE_LINEAR;
  24071. },
  24072. enumerable: true,
  24073. configurable: true
  24074. });
  24075. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24076. /**
  24077. * Texture used in all pbr material as the reflection texture.
  24078. * As in the majority of the scene they are the same (exception for multi room and so on),
  24079. * this is easier to reference from here than from all the materials.
  24080. */
  24081. get: function () {
  24082. return this._environmentTexture;
  24083. },
  24084. /**
  24085. * Texture used in all pbr material as the reflection texture.
  24086. * As in the majority of the scene they are the same (exception for multi room and so on),
  24087. * this is easier to set here than in all the materials.
  24088. */
  24089. set: function (value) {
  24090. if (this._environmentTexture === value) {
  24091. return;
  24092. }
  24093. this._environmentTexture = value;
  24094. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24100. /**
  24101. * Default image processing configuration used either in the rendering
  24102. * Forward main pass or through the imageProcessingPostProcess if present.
  24103. * As in the majority of the scene they are the same (exception for multi camera),
  24104. * this is easier to reference from here than from all the materials and post process.
  24105. *
  24106. * No setter as we it is a shared configuration, you can set the values instead.
  24107. */
  24108. get: function () {
  24109. return this._imageProcessingConfiguration;
  24110. },
  24111. enumerable: true,
  24112. configurable: true
  24113. });
  24114. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24115. get: function () {
  24116. return this._forceWireframe;
  24117. },
  24118. /**
  24119. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24120. */
  24121. set: function (value) {
  24122. if (this._forceWireframe === value) {
  24123. return;
  24124. }
  24125. this._forceWireframe = value;
  24126. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24127. },
  24128. enumerable: true,
  24129. configurable: true
  24130. });
  24131. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24132. get: function () {
  24133. return this._forcePointsCloud;
  24134. },
  24135. /**
  24136. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24137. */
  24138. set: function (value) {
  24139. if (this._forcePointsCloud === value) {
  24140. return;
  24141. }
  24142. this._forcePointsCloud = value;
  24143. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24144. },
  24145. enumerable: true,
  24146. configurable: true
  24147. });
  24148. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24149. /**
  24150. * Gets or sets the animation properties override
  24151. */
  24152. get: function () {
  24153. return this._animationPropertiesOverride;
  24154. },
  24155. set: function (value) {
  24156. this._animationPropertiesOverride = value;
  24157. },
  24158. enumerable: true,
  24159. configurable: true
  24160. });
  24161. Object.defineProperty(Scene.prototype, "onDispose", {
  24162. /** Sets a function to be executed when this scene is disposed. */
  24163. set: function (callback) {
  24164. if (this._onDisposeObserver) {
  24165. this.onDisposeObservable.remove(this._onDisposeObserver);
  24166. }
  24167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. Object.defineProperty(Scene.prototype, "beforeRender", {
  24173. /** Sets a function to be executed before rendering this scene */
  24174. set: function (callback) {
  24175. if (this._onBeforeRenderObserver) {
  24176. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24177. }
  24178. if (callback) {
  24179. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24180. }
  24181. },
  24182. enumerable: true,
  24183. configurable: true
  24184. });
  24185. Object.defineProperty(Scene.prototype, "afterRender", {
  24186. /** Sets a function to be executed after rendering this scene */
  24187. set: function (callback) {
  24188. if (this._onAfterRenderObserver) {
  24189. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24190. }
  24191. if (callback) {
  24192. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24193. }
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24199. /** Sets a function to be executed before rendering a camera*/
  24200. set: function (callback) {
  24201. if (this._onBeforeCameraRenderObserver) {
  24202. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24203. }
  24204. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24205. },
  24206. enumerable: true,
  24207. configurable: true
  24208. });
  24209. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24210. /** Sets a function to be executed after rendering a camera*/
  24211. set: function (callback) {
  24212. if (this._onAfterCameraRenderObserver) {
  24213. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24214. }
  24215. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24216. },
  24217. enumerable: true,
  24218. configurable: true
  24219. });
  24220. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24221. /**
  24222. * Gets the gamepad manager associated with the scene
  24223. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24224. */
  24225. get: function () {
  24226. if (!this._gamepadManager) {
  24227. this._gamepadManager = new BABYLON.GamepadManager(this);
  24228. }
  24229. return this._gamepadManager;
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24235. /**
  24236. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24237. */
  24238. get: function () {
  24239. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24245. get: function () {
  24246. return this._useRightHandedSystem;
  24247. },
  24248. /**
  24249. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24250. */
  24251. set: function (value) {
  24252. if (this._useRightHandedSystem === value) {
  24253. return;
  24254. }
  24255. this._useRightHandedSystem = value;
  24256. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24257. },
  24258. enumerable: true,
  24259. configurable: true
  24260. });
  24261. /**
  24262. * Sets the step Id used by deterministic lock step
  24263. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24264. * @param newStepId defines the step Id
  24265. */
  24266. Scene.prototype.setStepId = function (newStepId) {
  24267. this._currentStepId = newStepId;
  24268. };
  24269. ;
  24270. /**
  24271. * Gets the step Id used by deterministic lock step
  24272. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24273. * @returns the step Id
  24274. */
  24275. Scene.prototype.getStepId = function () {
  24276. return this._currentStepId;
  24277. };
  24278. ;
  24279. /**
  24280. * Gets the internal step used by deterministic lock step
  24281. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24282. * @returns the internal step
  24283. */
  24284. Scene.prototype.getInternalStep = function () {
  24285. return this._currentInternalStep;
  24286. };
  24287. ;
  24288. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24289. get: function () {
  24290. return this._fogEnabled;
  24291. },
  24292. /**
  24293. * Gets or sets a boolean indicating if fog is enabled on this scene
  24294. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24295. */
  24296. set: function (value) {
  24297. if (this._fogEnabled === value) {
  24298. return;
  24299. }
  24300. this._fogEnabled = value;
  24301. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24302. },
  24303. enumerable: true,
  24304. configurable: true
  24305. });
  24306. Object.defineProperty(Scene.prototype, "fogMode", {
  24307. get: function () {
  24308. return this._fogMode;
  24309. },
  24310. /**
  24311. * Gets or sets the fog mode to use
  24312. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24313. */
  24314. set: function (value) {
  24315. if (this._fogMode === value) {
  24316. return;
  24317. }
  24318. this._fogMode = value;
  24319. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24320. },
  24321. enumerable: true,
  24322. configurable: true
  24323. });
  24324. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24325. get: function () {
  24326. return this._shadowsEnabled;
  24327. },
  24328. /**
  24329. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24330. */
  24331. set: function (value) {
  24332. if (this._shadowsEnabled === value) {
  24333. return;
  24334. }
  24335. this._shadowsEnabled = value;
  24336. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24337. },
  24338. enumerable: true,
  24339. configurable: true
  24340. });
  24341. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24342. get: function () {
  24343. return this._lightsEnabled;
  24344. },
  24345. /**
  24346. * Gets or sets a boolean indicating if lights are enabled on this scene
  24347. */
  24348. set: function (value) {
  24349. if (this._lightsEnabled === value) {
  24350. return;
  24351. }
  24352. this._lightsEnabled = value;
  24353. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24354. },
  24355. enumerable: true,
  24356. configurable: true
  24357. });
  24358. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24359. /** The default material used on meshes when no material is affected */
  24360. get: function () {
  24361. if (!this._defaultMaterial) {
  24362. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24363. }
  24364. return this._defaultMaterial;
  24365. },
  24366. /** The default material used on meshes when no material is affected */
  24367. set: function (value) {
  24368. this._defaultMaterial = value;
  24369. },
  24370. enumerable: true,
  24371. configurable: true
  24372. });
  24373. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24374. get: function () {
  24375. return this._texturesEnabled;
  24376. },
  24377. /**
  24378. * Gets or sets a boolean indicating if textures are enabled on this scene
  24379. */
  24380. set: function (value) {
  24381. if (this._texturesEnabled === value) {
  24382. return;
  24383. }
  24384. this._texturesEnabled = value;
  24385. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24391. get: function () {
  24392. return this._skeletonsEnabled;
  24393. },
  24394. /**
  24395. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24396. */
  24397. set: function (value) {
  24398. if (this._skeletonsEnabled === value) {
  24399. return;
  24400. }
  24401. this._skeletonsEnabled = value;
  24402. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24403. },
  24404. enumerable: true,
  24405. configurable: true
  24406. });
  24407. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24408. /**
  24409. * Gets the postprocess render pipeline manager
  24410. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24411. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24412. */
  24413. get: function () {
  24414. if (!this._postProcessRenderPipelineManager) {
  24415. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24416. }
  24417. return this._postProcessRenderPipelineManager;
  24418. },
  24419. enumerable: true,
  24420. configurable: true
  24421. });
  24422. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24423. /**
  24424. * Gets the main soundtrack associated with the scene
  24425. */
  24426. get: function () {
  24427. if (!this._mainSoundTrack) {
  24428. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24429. }
  24430. return this._mainSoundTrack;
  24431. },
  24432. enumerable: true,
  24433. configurable: true
  24434. });
  24435. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24436. /** @hidden */
  24437. get: function () {
  24438. return this._alternateRendering;
  24439. },
  24440. enumerable: true,
  24441. configurable: true
  24442. });
  24443. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24444. /**
  24445. * Gets the list of frustum planes (built from the active camera)
  24446. */
  24447. get: function () {
  24448. return this._frustumPlanes;
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24454. /**
  24455. * Gets the current geometry buffer associated to the scene.
  24456. */
  24457. get: function () {
  24458. return this._geometryBufferRenderer;
  24459. },
  24460. /**
  24461. * Sets the current geometry buffer for the scene.
  24462. */
  24463. set: function (geometryBufferRenderer) {
  24464. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24465. this._geometryBufferRenderer = geometryBufferRenderer;
  24466. }
  24467. },
  24468. enumerable: true,
  24469. configurable: true
  24470. });
  24471. Object.defineProperty(Scene.prototype, "debugLayer", {
  24472. /**
  24473. * Gets the debug layer associated with the scene
  24474. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24475. */
  24476. get: function () {
  24477. if (!this._debugLayer) {
  24478. this._debugLayer = new BABYLON.DebugLayer(this);
  24479. }
  24480. return this._debugLayer;
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24486. /**
  24487. * Gets a boolean indicating if collisions are processed on a web worker
  24488. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24489. */
  24490. get: function () {
  24491. return this._workerCollisions;
  24492. },
  24493. set: function (enabled) {
  24494. if (!BABYLON.CollisionCoordinatorLegacy) {
  24495. return;
  24496. }
  24497. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24498. this._workerCollisions = enabled;
  24499. if (this.collisionCoordinator) {
  24500. this.collisionCoordinator.destroy();
  24501. }
  24502. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24503. this.collisionCoordinator.init(this);
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24509. /**
  24510. * Gets the octree used to boost mesh selection (picking)
  24511. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24512. */
  24513. get: function () {
  24514. return this._selectionOctree;
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24520. /**
  24521. * Gets the mesh that is currently under the pointer
  24522. */
  24523. get: function () {
  24524. return this._pointerOverMesh;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "pointerX", {
  24530. /**
  24531. * Gets the current on-screen X position of the pointer
  24532. */
  24533. get: function () {
  24534. return this._pointerX;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "pointerY", {
  24540. /**
  24541. * Gets the current on-screen Y position of the pointer
  24542. */
  24543. get: function () {
  24544. return this._pointerY;
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. /**
  24550. * Gets the cached material (ie. the latest rendered one)
  24551. * @returns the cached material
  24552. */
  24553. Scene.prototype.getCachedMaterial = function () {
  24554. return this._cachedMaterial;
  24555. };
  24556. /**
  24557. * Gets the cached effect (ie. the latest rendered one)
  24558. * @returns the cached effect
  24559. */
  24560. Scene.prototype.getCachedEffect = function () {
  24561. return this._cachedEffect;
  24562. };
  24563. /**
  24564. * Gets the cached visibility state (ie. the latest rendered one)
  24565. * @returns the cached visibility state
  24566. */
  24567. Scene.prototype.getCachedVisibility = function () {
  24568. return this._cachedVisibility;
  24569. };
  24570. /**
  24571. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24572. * @param material defines the current material
  24573. * @param effect defines the current effect
  24574. * @param visibility defines the current visibility state
  24575. * @returns true if one parameter is not cached
  24576. */
  24577. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24578. if (visibility === void 0) { visibility = 1; }
  24579. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24580. };
  24581. /**
  24582. * Gets the bounding box renderer associated with the scene
  24583. * @returns a BoundingBoxRenderer
  24584. */
  24585. Scene.prototype.getBoundingBoxRenderer = function () {
  24586. if (!this._boundingBoxRenderer) {
  24587. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24588. }
  24589. return this._boundingBoxRenderer;
  24590. };
  24591. /**
  24592. * Gets the outline renderer associated with the scene
  24593. * @returns a OutlineRenderer
  24594. */
  24595. Scene.prototype.getOutlineRenderer = function () {
  24596. return this._outlineRenderer;
  24597. };
  24598. /**
  24599. * Gets the engine associated with the scene
  24600. * @returns an Engine
  24601. */
  24602. Scene.prototype.getEngine = function () {
  24603. return this._engine;
  24604. };
  24605. /**
  24606. * Gets the total number of vertices rendered per frame
  24607. * @returns the total number of vertices rendered per frame
  24608. */
  24609. Scene.prototype.getTotalVertices = function () {
  24610. return this._totalVertices.current;
  24611. };
  24612. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24613. /**
  24614. * Gets the performance counter for total vertices
  24615. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24616. */
  24617. get: function () {
  24618. return this._totalVertices;
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. /**
  24624. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24625. * @returns the total number of active indices rendered per frame
  24626. */
  24627. Scene.prototype.getActiveIndices = function () {
  24628. return this._activeIndices.current;
  24629. };
  24630. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24631. /**
  24632. * Gets the performance counter for active indices
  24633. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24634. */
  24635. get: function () {
  24636. return this._activeIndices;
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. /**
  24642. * Gets the total number of active particles rendered per frame
  24643. * @returns the total number of active particles rendered per frame
  24644. */
  24645. Scene.prototype.getActiveParticles = function () {
  24646. return this._activeParticles.current;
  24647. };
  24648. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24649. /**
  24650. * Gets the performance counter for active particles
  24651. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24652. */
  24653. get: function () {
  24654. return this._activeParticles;
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. /**
  24660. * Gets the total number of active bones rendered per frame
  24661. * @returns the total number of active bones rendered per frame
  24662. */
  24663. Scene.prototype.getActiveBones = function () {
  24664. return this._activeBones.current;
  24665. };
  24666. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24667. /**
  24668. * Gets the performance counter for active bones
  24669. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24670. */
  24671. get: function () {
  24672. return this._activeBones;
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. /** @hidden */
  24678. Scene.prototype.getInterFramePerfCounter = function () {
  24679. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24680. return 0;
  24681. };
  24682. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24683. /** @hidden */
  24684. get: function () {
  24685. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24686. return null;
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. /** @hidden */
  24692. Scene.prototype.getLastFrameDuration = function () {
  24693. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24694. return 0;
  24695. };
  24696. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24697. /** @hidden */
  24698. get: function () {
  24699. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24700. return null;
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. /** @hidden */
  24706. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24707. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24708. return 0;
  24709. };
  24710. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24711. /** @hidden */
  24712. get: function () {
  24713. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24714. return null;
  24715. },
  24716. enumerable: true,
  24717. configurable: true
  24718. });
  24719. /**
  24720. * Gets the array of active meshes
  24721. * @returns an array of AbstractMesh
  24722. */
  24723. Scene.prototype.getActiveMeshes = function () {
  24724. return this._activeMeshes;
  24725. };
  24726. /** @hidden */
  24727. Scene.prototype.getRenderTargetsDuration = function () {
  24728. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24729. return 0;
  24730. };
  24731. /** @hidden */
  24732. Scene.prototype.getRenderDuration = function () {
  24733. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24734. return 0;
  24735. };
  24736. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24737. /** @hidden */
  24738. get: function () {
  24739. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24740. return null;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. /** @hidden */
  24746. Scene.prototype.getParticlesDuration = function () {
  24747. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24748. return 0;
  24749. };
  24750. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24751. /** @hidden */
  24752. get: function () {
  24753. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24754. return null;
  24755. },
  24756. enumerable: true,
  24757. configurable: true
  24758. });
  24759. /** @hidden */
  24760. Scene.prototype.getSpritesDuration = function () {
  24761. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24762. return 0;
  24763. };
  24764. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24765. /** @hidden */
  24766. get: function () {
  24767. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24768. return null;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. /**
  24774. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24775. * @returns a number
  24776. */
  24777. Scene.prototype.getAnimationRatio = function () {
  24778. return this._animationRatio;
  24779. };
  24780. /**
  24781. * Gets an unique Id for the current frame
  24782. * @returns a number
  24783. */
  24784. Scene.prototype.getRenderId = function () {
  24785. return this._renderId;
  24786. };
  24787. /** Call this function if you want to manually increment the render Id*/
  24788. Scene.prototype.incrementRenderId = function () {
  24789. this._renderId++;
  24790. };
  24791. Scene.prototype._updatePointerPosition = function (evt) {
  24792. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24793. if (!canvasRect) {
  24794. return;
  24795. }
  24796. this._pointerX = evt.clientX - canvasRect.left;
  24797. this._pointerY = evt.clientY - canvasRect.top;
  24798. this._unTranslatedPointerX = this._pointerX;
  24799. this._unTranslatedPointerY = this._pointerY;
  24800. };
  24801. Scene.prototype._createUbo = function () {
  24802. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24803. this._sceneUbo.addUniform("viewProjection", 16);
  24804. this._sceneUbo.addUniform("view", 16);
  24805. };
  24806. Scene.prototype._createAlternateUbo = function () {
  24807. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24808. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24809. this._alternateSceneUbo.addUniform("view", 16);
  24810. };
  24811. // Pointers handling
  24812. /**
  24813. * Use this method to simulate a pointer move on a mesh
  24814. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24815. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24816. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24817. * @returns the current scene
  24818. */
  24819. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24820. var evt = new PointerEvent("pointermove", pointerEventInit);
  24821. return this._processPointerMove(pickResult, evt);
  24822. };
  24823. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24824. var canvas = this._engine.getRenderingCanvas();
  24825. if (!canvas) {
  24826. return this;
  24827. }
  24828. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24829. this.setPointerOverSprite(null);
  24830. this.setPointerOverMesh(pickResult.pickedMesh);
  24831. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24832. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24833. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24834. }
  24835. else {
  24836. canvas.style.cursor = this.hoverCursor;
  24837. }
  24838. }
  24839. else {
  24840. canvas.style.cursor = this.defaultCursor;
  24841. }
  24842. }
  24843. else {
  24844. this.setPointerOverMesh(null);
  24845. // Sprites
  24846. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24847. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24848. this.setPointerOverSprite(pickResult.pickedSprite);
  24849. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24850. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24851. }
  24852. else {
  24853. canvas.style.cursor = this.hoverCursor;
  24854. }
  24855. }
  24856. else {
  24857. this.setPointerOverSprite(null);
  24858. // Restore pointer
  24859. canvas.style.cursor = this.defaultCursor;
  24860. }
  24861. }
  24862. if (pickResult) {
  24863. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24864. if (this.onPointerMove) {
  24865. this.onPointerMove(evt, pickResult, type);
  24866. }
  24867. if (this.onPointerObservable.hasObservers()) {
  24868. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24869. this.onPointerObservable.notifyObservers(pi, type);
  24870. }
  24871. }
  24872. return this;
  24873. };
  24874. /**
  24875. * Use this method to simulate a pointer down on a mesh
  24876. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24877. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24878. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24879. * @returns the current scene
  24880. */
  24881. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24882. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24883. return this._processPointerDown(pickResult, evt);
  24884. };
  24885. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24886. var _this = this;
  24887. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24888. this._pickedDownMesh = pickResult.pickedMesh;
  24889. var actionManager = pickResult.pickedMesh.actionManager;
  24890. if (actionManager) {
  24891. if (actionManager.hasPickTriggers) {
  24892. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24893. switch (evt.button) {
  24894. case 0:
  24895. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24896. break;
  24897. case 1:
  24898. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24899. break;
  24900. case 2:
  24901. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24902. break;
  24903. }
  24904. }
  24905. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24906. window.setTimeout(function () {
  24907. 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);
  24908. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24909. if (_this._totalPointersPressed !== 0 &&
  24910. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24911. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24912. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24913. _this._startingPointerTime = 0;
  24914. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24915. }
  24916. }
  24917. }, Scene.LongPressDelay);
  24918. }
  24919. }
  24920. }
  24921. if (pickResult) {
  24922. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24923. if (this.onPointerDown) {
  24924. this.onPointerDown(evt, pickResult, type);
  24925. }
  24926. if (this.onPointerObservable.hasObservers()) {
  24927. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24928. this.onPointerObservable.notifyObservers(pi, type);
  24929. }
  24930. }
  24931. return this;
  24932. };
  24933. /**
  24934. * Use this method to simulate a pointer up on a mesh
  24935. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24936. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24937. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24938. * @returns the current scene
  24939. */
  24940. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24941. var evt = new PointerEvent("pointerup", pointerEventInit);
  24942. var clickInfo = new ClickInfo();
  24943. clickInfo.singleClick = true;
  24944. clickInfo.ignore = true;
  24945. return this._processPointerUp(pickResult, evt, clickInfo);
  24946. };
  24947. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24948. if (pickResult && pickResult && pickResult.pickedMesh) {
  24949. this._pickedUpMesh = pickResult.pickedMesh;
  24950. if (this._pickedDownMesh === this._pickedUpMesh) {
  24951. if (this.onPointerPick) {
  24952. this.onPointerPick(evt, pickResult);
  24953. }
  24954. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24955. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24956. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24957. this.onPointerObservable.notifyObservers(pi, type_1);
  24958. }
  24959. }
  24960. if (pickResult.pickedMesh.actionManager) {
  24961. if (clickInfo.ignore) {
  24962. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24963. }
  24964. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24965. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24966. }
  24967. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24968. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24969. }
  24970. }
  24971. }
  24972. if (this._pickedDownMesh &&
  24973. this._pickedDownMesh.actionManager &&
  24974. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24975. this._pickedDownMesh !== this._pickedUpMesh) {
  24976. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24977. }
  24978. var type = BABYLON.PointerEventTypes.POINTERUP;
  24979. if (this.onPointerObservable.hasObservers()) {
  24980. if (!clickInfo.ignore) {
  24981. if (!clickInfo.hasSwiped) {
  24982. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24983. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24984. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24985. this.onPointerObservable.notifyObservers(pi, type_2);
  24986. }
  24987. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24988. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24989. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24990. this.onPointerObservable.notifyObservers(pi, type_3);
  24991. }
  24992. }
  24993. }
  24994. else {
  24995. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24996. this.onPointerObservable.notifyObservers(pi, type);
  24997. }
  24998. }
  24999. if (this.onPointerUp) {
  25000. this.onPointerUp(evt, pickResult, type);
  25001. }
  25002. return this;
  25003. };
  25004. /**
  25005. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25006. * @param attachUp defines if you want to attach events to pointerup
  25007. * @param attachDown defines if you want to attach events to pointerdown
  25008. * @param attachMove defines if you want to attach events to pointermove
  25009. */
  25010. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25011. var _this = this;
  25012. if (attachUp === void 0) { attachUp = true; }
  25013. if (attachDown === void 0) { attachDown = true; }
  25014. if (attachMove === void 0) { attachMove = true; }
  25015. this._initActionManager = function (act, clickInfo) {
  25016. if (!_this._meshPickProceed) {
  25017. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25018. _this._currentPickResult = pickResult;
  25019. if (pickResult) {
  25020. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25021. }
  25022. _this._meshPickProceed = true;
  25023. }
  25024. return act;
  25025. };
  25026. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25027. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25028. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25029. btn !== _this._previousButtonPressed) {
  25030. _this._doubleClickOccured = false;
  25031. clickInfo.singleClick = true;
  25032. clickInfo.ignore = false;
  25033. cb(clickInfo, _this._currentPickResult);
  25034. }
  25035. };
  25036. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25037. var clickInfo = new ClickInfo();
  25038. _this._currentPickResult = null;
  25039. var act = null;
  25040. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25041. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25042. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25043. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25044. act = _this._initActionManager(act, clickInfo);
  25045. if (act)
  25046. checkPicking = act.hasPickTriggers;
  25047. }
  25048. if (checkPicking) {
  25049. var btn = evt.button;
  25050. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25051. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25052. if (!clickInfo.hasSwiped) {
  25053. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25054. if (!checkSingleClickImmediately) {
  25055. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25056. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25057. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25058. act = _this._initActionManager(act, clickInfo);
  25059. if (act)
  25060. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25061. }
  25062. }
  25063. if (checkSingleClickImmediately) {
  25064. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25065. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25066. btn !== _this._previousButtonPressed) {
  25067. clickInfo.singleClick = true;
  25068. cb(clickInfo, _this._currentPickResult);
  25069. }
  25070. }
  25071. // at least one double click is required to be check and exclusive double click is enabled
  25072. else {
  25073. // wait that no double click has been raised during the double click delay
  25074. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25075. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25076. }
  25077. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25078. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25079. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25080. act = _this._initActionManager(act, clickInfo);
  25081. if (act)
  25082. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25083. }
  25084. if (checkDoubleClick) {
  25085. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25086. if (btn === _this._previousButtonPressed &&
  25087. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25088. !_this._doubleClickOccured) {
  25089. // pointer has not moved for 2 clicks, it's a double click
  25090. if (!clickInfo.hasSwiped &&
  25091. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25092. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25093. _this._previousStartingPointerTime = 0;
  25094. _this._doubleClickOccured = true;
  25095. clickInfo.doubleClick = true;
  25096. clickInfo.ignore = false;
  25097. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25098. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25099. }
  25100. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25101. cb(clickInfo, _this._currentPickResult);
  25102. }
  25103. // if the two successive clicks are too far, it's just two simple clicks
  25104. else {
  25105. _this._doubleClickOccured = false;
  25106. _this._previousStartingPointerTime = _this._startingPointerTime;
  25107. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25108. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25109. _this._previousButtonPressed = btn;
  25110. if (Scene.ExclusiveDoubleClickMode) {
  25111. if (_this._previousDelayedSimpleClickTimeout) {
  25112. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25113. }
  25114. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25115. cb(clickInfo, _this._previousPickResult);
  25116. }
  25117. else {
  25118. cb(clickInfo, _this._currentPickResult);
  25119. }
  25120. }
  25121. }
  25122. // just the first click of the double has been raised
  25123. else {
  25124. _this._doubleClickOccured = false;
  25125. _this._previousStartingPointerTime = _this._startingPointerTime;
  25126. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25127. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25128. _this._previousButtonPressed = btn;
  25129. }
  25130. }
  25131. }
  25132. }
  25133. clickInfo.ignore = true;
  25134. cb(clickInfo, _this._currentPickResult);
  25135. };
  25136. this._spritePredicate = function (sprite) {
  25137. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25138. };
  25139. this._onPointerMove = function (evt) {
  25140. _this._updatePointerPosition(evt);
  25141. // PreObservable support
  25142. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25143. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25144. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25145. _this.onPrePointerObservable.notifyObservers(pi, type);
  25146. if (pi.skipOnPointerObservable) {
  25147. return;
  25148. }
  25149. }
  25150. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25151. return;
  25152. }
  25153. if (!_this.pointerMovePredicate) {
  25154. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25155. }
  25156. // Meshes
  25157. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25158. _this._processPointerMove(pickResult, evt);
  25159. };
  25160. this._onPointerDown = function (evt) {
  25161. _this._totalPointersPressed++;
  25162. _this._pickedDownMesh = null;
  25163. _this._meshPickProceed = false;
  25164. _this._updatePointerPosition(evt);
  25165. if (_this.preventDefaultOnPointerDown && canvas) {
  25166. evt.preventDefault();
  25167. canvas.focus();
  25168. }
  25169. // PreObservable support
  25170. if (_this.onPrePointerObservable.hasObservers()) {
  25171. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25172. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25173. _this.onPrePointerObservable.notifyObservers(pi, type);
  25174. if (pi.skipOnPointerObservable) {
  25175. return;
  25176. }
  25177. }
  25178. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25179. return;
  25180. }
  25181. _this._pointerCaptures[evt.pointerId] = true;
  25182. _this._startingPointerPosition.x = _this._pointerX;
  25183. _this._startingPointerPosition.y = _this._pointerY;
  25184. _this._startingPointerTime = Date.now();
  25185. if (!_this.pointerDownPredicate) {
  25186. _this.pointerDownPredicate = function (mesh) {
  25187. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25188. };
  25189. }
  25190. // Meshes
  25191. _this._pickedDownMesh = null;
  25192. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25193. _this._processPointerDown(pickResult, evt);
  25194. // Sprites
  25195. _this._pickedDownSprite = null;
  25196. if (_this.spriteManagers.length > 0) {
  25197. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25198. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25199. if (pickResult.pickedSprite.actionManager) {
  25200. _this._pickedDownSprite = pickResult.pickedSprite;
  25201. switch (evt.button) {
  25202. case 0:
  25203. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25204. break;
  25205. case 1:
  25206. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25207. break;
  25208. case 2:
  25209. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25210. break;
  25211. }
  25212. if (pickResult.pickedSprite.actionManager) {
  25213. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25214. }
  25215. }
  25216. }
  25217. }
  25218. };
  25219. this._onPointerUp = function (evt) {
  25220. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25221. return; // So we need to test it the pointer down was pressed before.
  25222. }
  25223. _this._totalPointersPressed--;
  25224. _this._pickedUpMesh = null;
  25225. _this._meshPickProceed = false;
  25226. _this._updatePointerPosition(evt);
  25227. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25228. // PreObservable support
  25229. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25230. if (!clickInfo.ignore) {
  25231. if (!clickInfo.hasSwiped) {
  25232. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25233. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25234. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25235. _this.onPrePointerObservable.notifyObservers(pi, type);
  25236. if (pi.skipOnPointerObservable) {
  25237. return;
  25238. }
  25239. }
  25240. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25241. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25242. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25243. _this.onPrePointerObservable.notifyObservers(pi, type);
  25244. if (pi.skipOnPointerObservable) {
  25245. return;
  25246. }
  25247. }
  25248. }
  25249. }
  25250. else {
  25251. var type = BABYLON.PointerEventTypes.POINTERUP;
  25252. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25253. _this.onPrePointerObservable.notifyObservers(pi, type);
  25254. if (pi.skipOnPointerObservable) {
  25255. return;
  25256. }
  25257. }
  25258. }
  25259. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25260. return;
  25261. }
  25262. _this._pointerCaptures[evt.pointerId] = false;
  25263. if (!_this.pointerUpPredicate) {
  25264. _this.pointerUpPredicate = function (mesh) {
  25265. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25266. };
  25267. }
  25268. // Meshes
  25269. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25270. _this._initActionManager(null, clickInfo);
  25271. }
  25272. if (!pickResult) {
  25273. pickResult = _this._currentPickResult;
  25274. }
  25275. _this._processPointerUp(pickResult, evt, clickInfo);
  25276. // Sprites
  25277. if (!clickInfo.ignore) {
  25278. if (_this.spriteManagers.length > 0) {
  25279. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25280. if (spritePickResult) {
  25281. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25282. if (spritePickResult.pickedSprite.actionManager) {
  25283. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25284. if (spritePickResult.pickedSprite.actionManager) {
  25285. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25286. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25287. }
  25288. }
  25289. }
  25290. }
  25291. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25292. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25293. }
  25294. }
  25295. }
  25296. }
  25297. _this._previousPickResult = _this._currentPickResult;
  25298. });
  25299. };
  25300. this._onKeyDown = function (evt) {
  25301. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25302. if (_this.onPreKeyboardObservable.hasObservers()) {
  25303. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25304. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25305. if (pi.skipOnPointerObservable) {
  25306. return;
  25307. }
  25308. }
  25309. if (_this.onKeyboardObservable.hasObservers()) {
  25310. var pi = new BABYLON.KeyboardInfo(type, evt);
  25311. _this.onKeyboardObservable.notifyObservers(pi, type);
  25312. }
  25313. if (_this.actionManager) {
  25314. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25315. }
  25316. };
  25317. this._onKeyUp = function (evt) {
  25318. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25319. if (_this.onPreKeyboardObservable.hasObservers()) {
  25320. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25321. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25322. if (pi.skipOnPointerObservable) {
  25323. return;
  25324. }
  25325. }
  25326. if (_this.onKeyboardObservable.hasObservers()) {
  25327. var pi = new BABYLON.KeyboardInfo(type, evt);
  25328. _this.onKeyboardObservable.notifyObservers(pi, type);
  25329. }
  25330. if (_this.actionManager) {
  25331. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25332. }
  25333. };
  25334. var engine = this.getEngine();
  25335. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25336. if (!canvas) {
  25337. return;
  25338. }
  25339. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25340. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25341. });
  25342. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25343. if (!canvas) {
  25344. return;
  25345. }
  25346. canvas.removeEventListener("keydown", _this._onKeyDown);
  25347. canvas.removeEventListener("keyup", _this._onKeyUp);
  25348. });
  25349. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25350. var canvas = this._engine.getRenderingCanvas();
  25351. if (!canvas) {
  25352. return;
  25353. }
  25354. if (attachMove) {
  25355. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25356. // Wheel
  25357. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25358. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25359. }
  25360. if (attachDown) {
  25361. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25362. }
  25363. if (attachUp) {
  25364. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25365. }
  25366. canvas.tabIndex = 1;
  25367. };
  25368. /** Detaches all event handlers*/
  25369. Scene.prototype.detachControl = function () {
  25370. var engine = this.getEngine();
  25371. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25372. var canvas = engine.getRenderingCanvas();
  25373. if (!canvas) {
  25374. return;
  25375. }
  25376. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25377. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25378. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25379. if (this._onCanvasBlurObserver) {
  25380. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25381. }
  25382. if (this._onCanvasFocusObserver) {
  25383. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25384. }
  25385. // Wheel
  25386. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25387. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25388. // Keyboard
  25389. canvas.removeEventListener("keydown", this._onKeyDown);
  25390. canvas.removeEventListener("keyup", this._onKeyUp);
  25391. // Observables
  25392. this.onKeyboardObservable.clear();
  25393. this.onPreKeyboardObservable.clear();
  25394. this.onPointerObservable.clear();
  25395. this.onPrePointerObservable.clear();
  25396. };
  25397. /**
  25398. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25399. * Delay loaded resources are not taking in account
  25400. * @return true if all required resources are ready
  25401. */
  25402. Scene.prototype.isReady = function () {
  25403. if (this._isDisposed) {
  25404. return false;
  25405. }
  25406. if (this._pendingData.length > 0) {
  25407. return false;
  25408. }
  25409. var index;
  25410. var engine = this.getEngine();
  25411. // Geometries
  25412. for (index = 0; index < this._geometries.length; index++) {
  25413. var geometry = this._geometries[index];
  25414. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25415. return false;
  25416. }
  25417. }
  25418. // Meshes
  25419. for (index = 0; index < this.meshes.length; index++) {
  25420. var mesh = this.meshes[index];
  25421. if (!mesh.isEnabled()) {
  25422. continue;
  25423. }
  25424. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25425. continue;
  25426. }
  25427. if (!mesh.isReady(true)) {
  25428. return false;
  25429. }
  25430. // Effect layers
  25431. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25432. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25433. var layer = _a[_i];
  25434. if (!layer.hasMesh(mesh)) {
  25435. continue;
  25436. }
  25437. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25438. var subMesh = _c[_b];
  25439. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25440. return false;
  25441. }
  25442. }
  25443. }
  25444. }
  25445. // Post-processes
  25446. if (this.activeCameras && this.activeCameras.length > 0) {
  25447. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25448. var camera = _e[_d];
  25449. if (!camera.isReady(true)) {
  25450. return false;
  25451. }
  25452. }
  25453. }
  25454. else if (this.activeCamera) {
  25455. if (!this.activeCamera.isReady(true)) {
  25456. return false;
  25457. }
  25458. }
  25459. // Particles
  25460. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25461. var particleSystem = _g[_f];
  25462. if (!particleSystem.isReady()) {
  25463. return false;
  25464. }
  25465. }
  25466. return true;
  25467. };
  25468. /** Resets all cached information relative to material (including effect and visibility) */
  25469. Scene.prototype.resetCachedMaterial = function () {
  25470. this._cachedMaterial = null;
  25471. this._cachedEffect = null;
  25472. this._cachedVisibility = null;
  25473. };
  25474. /**
  25475. * Registers a function to be called before every frame render
  25476. * @param func defines the function to register
  25477. */
  25478. Scene.prototype.registerBeforeRender = function (func) {
  25479. this.onBeforeRenderObservable.add(func);
  25480. };
  25481. /**
  25482. * Unregisters a function called before every frame render
  25483. * @param func defines the function to unregister
  25484. */
  25485. Scene.prototype.unregisterBeforeRender = function (func) {
  25486. this.onBeforeRenderObservable.removeCallback(func);
  25487. };
  25488. /**
  25489. * Registers a function to be called after every frame render
  25490. * @param func defines the function to register
  25491. */
  25492. Scene.prototype.registerAfterRender = function (func) {
  25493. this.onAfterRenderObservable.add(func);
  25494. };
  25495. /**
  25496. * Unregisters a function called after every frame render
  25497. * @param func defines the function to unregister
  25498. */
  25499. Scene.prototype.unregisterAfterRender = function (func) {
  25500. this.onAfterRenderObservable.removeCallback(func);
  25501. };
  25502. Scene.prototype._executeOnceBeforeRender = function (func) {
  25503. var _this = this;
  25504. var execFunc = function () {
  25505. func();
  25506. setTimeout(function () {
  25507. _this.unregisterBeforeRender(execFunc);
  25508. });
  25509. };
  25510. this.registerBeforeRender(execFunc);
  25511. };
  25512. /**
  25513. * The provided function will run before render once and will be disposed afterwards.
  25514. * A timeout delay can be provided so that the function will be executed in N ms.
  25515. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25516. * @param func The function to be executed.
  25517. * @param timeout optional delay in ms
  25518. */
  25519. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25520. var _this = this;
  25521. if (timeout !== undefined) {
  25522. setTimeout(function () {
  25523. _this._executeOnceBeforeRender(func);
  25524. }, timeout);
  25525. }
  25526. else {
  25527. this._executeOnceBeforeRender(func);
  25528. }
  25529. };
  25530. /** @hidden */
  25531. Scene.prototype._addPendingData = function (data) {
  25532. this._pendingData.push(data);
  25533. };
  25534. /** @hidden */
  25535. Scene.prototype._removePendingData = function (data) {
  25536. var wasLoading = this.isLoading;
  25537. var index = this._pendingData.indexOf(data);
  25538. if (index !== -1) {
  25539. this._pendingData.splice(index, 1);
  25540. }
  25541. if (wasLoading && !this.isLoading) {
  25542. this.onDataLoadedObservable.notifyObservers(this);
  25543. }
  25544. };
  25545. /**
  25546. * Returns the number of items waiting to be loaded
  25547. * @returns the number of items waiting to be loaded
  25548. */
  25549. Scene.prototype.getWaitingItemsCount = function () {
  25550. return this._pendingData.length;
  25551. };
  25552. Object.defineProperty(Scene.prototype, "isLoading", {
  25553. /**
  25554. * Returns a boolean indicating if the scene is still loading data
  25555. */
  25556. get: function () {
  25557. return this._pendingData.length > 0;
  25558. },
  25559. enumerable: true,
  25560. configurable: true
  25561. });
  25562. /**
  25563. * Registers a function to be executed when the scene is ready
  25564. * @param {Function} func - the function to be executed
  25565. */
  25566. Scene.prototype.executeWhenReady = function (func) {
  25567. var _this = this;
  25568. this.onReadyObservable.add(func);
  25569. if (this._executeWhenReadyTimeoutId !== -1) {
  25570. return;
  25571. }
  25572. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25573. _this._checkIsReady();
  25574. }, 150);
  25575. };
  25576. /**
  25577. * Returns a promise that resolves when the scene is ready
  25578. * @returns A promise that resolves when the scene is ready
  25579. */
  25580. Scene.prototype.whenReadyAsync = function () {
  25581. var _this = this;
  25582. return new Promise(function (resolve) {
  25583. _this.executeWhenReady(function () {
  25584. resolve();
  25585. });
  25586. });
  25587. };
  25588. /** @hidden */
  25589. Scene.prototype._checkIsReady = function () {
  25590. var _this = this;
  25591. if (this.isReady()) {
  25592. this.onReadyObservable.notifyObservers(this);
  25593. this.onReadyObservable.clear();
  25594. this._executeWhenReadyTimeoutId = -1;
  25595. return;
  25596. }
  25597. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25598. _this._checkIsReady();
  25599. }, 150);
  25600. };
  25601. // Animations
  25602. /**
  25603. * Will start the animation sequence of a given target
  25604. * @param target defines the target
  25605. * @param from defines from which frame should animation start
  25606. * @param to defines until which frame should animation run.
  25607. * @param weight defines the weight to apply to the animation (1.0 by default)
  25608. * @param loop defines if the animation loops
  25609. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25610. * @param onAnimationEnd defines the function to be executed when the animation ends
  25611. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25612. * @returns the animatable object created for this animation
  25613. */
  25614. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25615. if (weight === void 0) { weight = 1.0; }
  25616. if (speedRatio === void 0) { speedRatio = 1.0; }
  25617. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25618. returnedAnimatable.weight = weight;
  25619. return returnedAnimatable;
  25620. };
  25621. /**
  25622. * Will start the animation sequence of a given target
  25623. * @param target defines the target
  25624. * @param from defines from which frame should animation start
  25625. * @param to defines until which frame should animation run.
  25626. * @param loop defines if the animation loops
  25627. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25628. * @param onAnimationEnd defines the function to be executed when the animation ends
  25629. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25630. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25631. * @returns the animatable object created for this animation
  25632. */
  25633. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25634. if (speedRatio === void 0) { speedRatio = 1.0; }
  25635. if (stopCurrent === void 0) { stopCurrent = true; }
  25636. if (from > to && speedRatio > 0) {
  25637. speedRatio *= -1;
  25638. }
  25639. if (stopCurrent) {
  25640. this.stopAnimation(target);
  25641. }
  25642. if (!animatable) {
  25643. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25644. }
  25645. // Local animations
  25646. if (target.animations) {
  25647. animatable.appendAnimations(target, target.animations);
  25648. }
  25649. // Children animations
  25650. if (target.getAnimatables) {
  25651. var animatables = target.getAnimatables();
  25652. for (var index = 0; index < animatables.length; index++) {
  25653. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25654. }
  25655. }
  25656. animatable.reset();
  25657. return animatable;
  25658. };
  25659. /**
  25660. * Begin a new animation on a given node
  25661. * @param target defines the target where the animation will take place
  25662. * @param animations defines the list of animations to start
  25663. * @param from defines the initial value
  25664. * @param to defines the final value
  25665. * @param loop defines if you want animation to loop (off by default)
  25666. * @param speedRatio defines the speed ratio to apply to all animations
  25667. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25668. * @returns the list of created animatables
  25669. */
  25670. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25671. if (speedRatio === undefined) {
  25672. speedRatio = 1.0;
  25673. }
  25674. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25675. return animatable;
  25676. };
  25677. /**
  25678. * Begin a new animation on a given node and its hierarchy
  25679. * @param target defines the root node where the animation will take place
  25680. * @param 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.
  25681. * @param animations defines the list of animations to start
  25682. * @param from defines the initial value
  25683. * @param to defines the final value
  25684. * @param loop defines if you want animation to loop (off by default)
  25685. * @param speedRatio defines the speed ratio to apply to all animations
  25686. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25687. * @returns the list of animatables created for all nodes
  25688. */
  25689. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25690. var children = target.getDescendants(directDescendantsOnly);
  25691. var result = [];
  25692. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25693. var child = children_1[_i];
  25694. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25695. }
  25696. return result;
  25697. };
  25698. /**
  25699. * Gets the animatable associated with a specific target
  25700. * @param target defines the target of the animatable
  25701. * @returns the required animatable if found
  25702. */
  25703. Scene.prototype.getAnimatableByTarget = function (target) {
  25704. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25705. if (this._activeAnimatables[index].target === target) {
  25706. return this._activeAnimatables[index];
  25707. }
  25708. }
  25709. return null;
  25710. };
  25711. /**
  25712. * Gets all animatables associated with a given target
  25713. * @param target defines the target to look animatables for
  25714. * @returns an array of Animatables
  25715. */
  25716. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25717. var result = [];
  25718. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25719. if (this._activeAnimatables[index].target === target) {
  25720. result.push(this._activeAnimatables[index]);
  25721. }
  25722. }
  25723. return result;
  25724. };
  25725. Object.defineProperty(Scene.prototype, "animatables", {
  25726. /**
  25727. * Gets all animatable attached to the scene
  25728. */
  25729. get: function () {
  25730. return this._activeAnimatables;
  25731. },
  25732. enumerable: true,
  25733. configurable: true
  25734. });
  25735. /**
  25736. * Will stop the animation of the given target
  25737. * @param target - the target
  25738. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25739. */
  25740. Scene.prototype.stopAnimation = function (target, animationName) {
  25741. var animatables = this.getAllAnimatablesByTarget(target);
  25742. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25743. var animatable = animatables_1[_i];
  25744. animatable.stop(animationName);
  25745. }
  25746. };
  25747. /**
  25748. * Stops and removes all animations that have been applied to the scene
  25749. */
  25750. Scene.prototype.stopAllAnimations = function () {
  25751. if (this._activeAnimatables) {
  25752. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25753. this._activeAnimatables[i].stop();
  25754. }
  25755. this._activeAnimatables = [];
  25756. }
  25757. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25758. var group = _a[_i];
  25759. group.stop();
  25760. }
  25761. };
  25762. Scene.prototype._animate = function () {
  25763. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25764. return;
  25765. }
  25766. // Getting time
  25767. var now = BABYLON.Tools.Now;
  25768. if (!this._animationTimeLast) {
  25769. if (this._pendingData.length > 0) {
  25770. return;
  25771. }
  25772. this._animationTimeLast = now;
  25773. }
  25774. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25775. this._animationTime += deltaTime;
  25776. this._animationTimeLast = now;
  25777. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25778. this._activeAnimatables[index]._animate(this._animationTime);
  25779. }
  25780. // Late animation bindings
  25781. this._processLateAnimationBindings();
  25782. };
  25783. /** @hidden */
  25784. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25785. var target = runtimeAnimation.target;
  25786. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25787. if (!target._lateAnimationHolders) {
  25788. target._lateAnimationHolders = {};
  25789. }
  25790. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25791. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25792. totalWeight: 0,
  25793. animations: [],
  25794. originalValue: originalValue
  25795. };
  25796. }
  25797. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25798. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25799. };
  25800. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25801. var normalizer = 1.0;
  25802. var finalPosition = BABYLON.Tmp.Vector3[0];
  25803. var finalScaling = BABYLON.Tmp.Vector3[1];
  25804. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25805. var startIndex = 0;
  25806. var originalAnimation = holder.animations[0];
  25807. var originalValue = holder.originalValue;
  25808. var scale = 1;
  25809. if (holder.totalWeight < 1.0) {
  25810. // We need to mix the original value in
  25811. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25812. scale = 1.0 - holder.totalWeight;
  25813. }
  25814. else {
  25815. startIndex = 1;
  25816. // We need to normalize the weights
  25817. normalizer = holder.totalWeight;
  25818. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25819. scale = originalAnimation.weight / normalizer;
  25820. if (scale == 1) {
  25821. return originalAnimation.currentValue;
  25822. }
  25823. }
  25824. finalScaling.scaleInPlace(scale);
  25825. finalPosition.scaleInPlace(scale);
  25826. finalQuaternion.scaleInPlace(scale);
  25827. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25828. var runtimeAnimation = holder.animations[animIndex];
  25829. var scale = runtimeAnimation.weight / normalizer;
  25830. var currentPosition = BABYLON.Tmp.Vector3[2];
  25831. var currentScaling = BABYLON.Tmp.Vector3[3];
  25832. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25833. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25834. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25835. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25836. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25837. }
  25838. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25839. return originalAnimation._workValue;
  25840. };
  25841. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25842. var originalAnimation = holder.animations[0];
  25843. var originalValue = holder.originalValue;
  25844. if (holder.animations.length === 1) {
  25845. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25846. }
  25847. var normalizer = 1.0;
  25848. var quaternions;
  25849. var weights;
  25850. if (holder.totalWeight < 1.0) {
  25851. var scale = 1.0 - holder.totalWeight;
  25852. quaternions = [];
  25853. weights = [];
  25854. quaternions.push(originalValue);
  25855. weights.push(scale);
  25856. }
  25857. else {
  25858. if (holder.animations.length === 2) { // Slerp as soon as we can
  25859. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25860. }
  25861. quaternions = [];
  25862. weights = [];
  25863. normalizer = holder.totalWeight;
  25864. }
  25865. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25866. var runtimeAnimation = holder.animations[animIndex];
  25867. quaternions.push(runtimeAnimation.currentValue);
  25868. weights.push(runtimeAnimation.weight / normalizer);
  25869. }
  25870. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25871. var cumulativeAmount = 0;
  25872. var cumulativeQuaternion = null;
  25873. for (var index = 0; index < quaternions.length;) {
  25874. if (!cumulativeQuaternion) {
  25875. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25876. cumulativeAmount = weights[index] + weights[index + 1];
  25877. index += 2;
  25878. continue;
  25879. }
  25880. cumulativeAmount += weights[index];
  25881. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25882. index++;
  25883. }
  25884. return cumulativeQuaternion;
  25885. };
  25886. Scene.prototype._processLateAnimationBindings = function () {
  25887. if (!this._registeredForLateAnimationBindings.length) {
  25888. return;
  25889. }
  25890. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25891. var target = this._registeredForLateAnimationBindings.data[index];
  25892. for (var path in target._lateAnimationHolders) {
  25893. var holder = target._lateAnimationHolders[path];
  25894. var originalAnimation = holder.animations[0];
  25895. var originalValue = holder.originalValue;
  25896. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25897. var finalValue = void 0;
  25898. if (matrixDecomposeMode) {
  25899. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25900. }
  25901. else {
  25902. var quaternionMode = originalValue.w !== undefined;
  25903. if (quaternionMode) {
  25904. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25905. }
  25906. else {
  25907. var startIndex = 0;
  25908. var normalizer = 1.0;
  25909. if (holder.totalWeight < 1.0) {
  25910. // We need to mix the original value in
  25911. if (originalValue.scale) {
  25912. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25913. }
  25914. else {
  25915. finalValue = originalValue * (1.0 - holder.totalWeight);
  25916. }
  25917. }
  25918. else {
  25919. // We need to normalize the weights
  25920. normalizer = holder.totalWeight;
  25921. var scale_1 = originalAnimation.weight / normalizer;
  25922. if (scale_1 !== 1) {
  25923. if (originalAnimation.currentValue.scale) {
  25924. finalValue = originalAnimation.currentValue.scale(scale_1);
  25925. }
  25926. else {
  25927. finalValue = originalAnimation.currentValue * scale_1;
  25928. }
  25929. }
  25930. else {
  25931. finalValue = originalAnimation.currentValue;
  25932. }
  25933. startIndex = 1;
  25934. }
  25935. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25936. var runtimeAnimation = holder.animations[animIndex];
  25937. var scale = runtimeAnimation.weight / normalizer;
  25938. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25939. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25940. }
  25941. else {
  25942. finalValue += runtimeAnimation.currentValue * scale;
  25943. }
  25944. }
  25945. }
  25946. }
  25947. target[path] = finalValue;
  25948. }
  25949. target._lateAnimationHolders = {};
  25950. }
  25951. this._registeredForLateAnimationBindings.reset();
  25952. };
  25953. // Matrix
  25954. /** @hidden */
  25955. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25956. this._useAlternateCameraConfiguration = active;
  25957. };
  25958. /**
  25959. * Gets the current view matrix
  25960. * @returns a Matrix
  25961. */
  25962. Scene.prototype.getViewMatrix = function () {
  25963. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25964. };
  25965. /**
  25966. * Gets the current projection matrix
  25967. * @returns a Matrix
  25968. */
  25969. Scene.prototype.getProjectionMatrix = function () {
  25970. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25971. };
  25972. /**
  25973. * Gets the current transform matrix
  25974. * @returns a Matrix made of View * Projection
  25975. */
  25976. Scene.prototype.getTransformMatrix = function () {
  25977. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25978. };
  25979. /**
  25980. * Sets the current transform matrix
  25981. * @param view defines the View matrix to use
  25982. * @param projection defines the Projection matrix to use
  25983. */
  25984. Scene.prototype.setTransformMatrix = function (view, projection) {
  25985. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25986. return;
  25987. }
  25988. this._viewUpdateFlag = view.updateFlag;
  25989. this._projectionUpdateFlag = projection.updateFlag;
  25990. this._viewMatrix = view;
  25991. this._projectionMatrix = projection;
  25992. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25993. // Update frustum
  25994. if (!this._frustumPlanes) {
  25995. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25996. }
  25997. else {
  25998. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25999. }
  26000. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26001. var otherCamera = this.activeCamera._alternateCamera;
  26002. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26003. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26004. }
  26005. if (this._sceneUbo.useUbo) {
  26006. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26007. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26008. this._sceneUbo.update();
  26009. }
  26010. };
  26011. /** @hidden */
  26012. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26013. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26014. return;
  26015. }
  26016. this._alternateViewUpdateFlag = view.updateFlag;
  26017. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26018. this._alternateViewMatrix = view;
  26019. this._alternateProjectionMatrix = projection;
  26020. if (!this._alternateTransformMatrix) {
  26021. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26022. }
  26023. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26024. if (!this._alternateSceneUbo) {
  26025. this._createAlternateUbo();
  26026. }
  26027. if (this._alternateSceneUbo.useUbo) {
  26028. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26029. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26030. this._alternateSceneUbo.update();
  26031. }
  26032. };
  26033. /**
  26034. * Gets the uniform buffer used to store scene data
  26035. * @returns a UniformBuffer
  26036. */
  26037. Scene.prototype.getSceneUniformBuffer = function () {
  26038. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26039. };
  26040. /**
  26041. * Gets an unique (relatively to the current scene) Id
  26042. * @returns an unique number for the scene
  26043. */
  26044. Scene.prototype.getUniqueId = function () {
  26045. var result = Scene._uniqueIdCounter;
  26046. Scene._uniqueIdCounter++;
  26047. return result;
  26048. };
  26049. /**
  26050. * Add a mesh to the list of scene's meshes
  26051. * @param newMesh defines the mesh to add
  26052. */
  26053. Scene.prototype.addMesh = function (newMesh) {
  26054. this.meshes.push(newMesh);
  26055. //notify the collision coordinator
  26056. if (this.collisionCoordinator) {
  26057. this.collisionCoordinator.onMeshAdded(newMesh);
  26058. }
  26059. newMesh._resyncLightSources();
  26060. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26061. };
  26062. /**
  26063. * Remove a mesh for the list of scene's meshes
  26064. * @param toRemove defines the mesh to remove
  26065. * @param recursive if all child meshes should also be removed from the scene
  26066. * @returns the index where the mesh was in the mesh list
  26067. */
  26068. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26069. var _this = this;
  26070. if (recursive === void 0) { recursive = false; }
  26071. var index = this.meshes.indexOf(toRemove);
  26072. if (index !== -1) {
  26073. // Remove from the scene if mesh found
  26074. this.meshes.splice(index, 1);
  26075. }
  26076. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26077. if (recursive) {
  26078. toRemove.getChildMeshes().forEach(function (m) {
  26079. _this.removeMesh(m);
  26080. });
  26081. }
  26082. return index;
  26083. };
  26084. /**
  26085. * Add a transform node to the list of scene's transform nodes
  26086. * @param newTransformNode defines the transform node to add
  26087. */
  26088. Scene.prototype.addTransformNode = function (newTransformNode) {
  26089. this.transformNodes.push(newTransformNode);
  26090. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26091. };
  26092. /**
  26093. * Remove a transform node for the list of scene's transform nodes
  26094. * @param toRemove defines the transform node to remove
  26095. * @returns the index where the transform node was in the transform node list
  26096. */
  26097. Scene.prototype.removeTransformNode = function (toRemove) {
  26098. var index = this.transformNodes.indexOf(toRemove);
  26099. if (index !== -1) {
  26100. // Remove from the scene if found
  26101. this.transformNodes.splice(index, 1);
  26102. }
  26103. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26104. return index;
  26105. };
  26106. /**
  26107. * Remove a skeleton for the list of scene's skeletons
  26108. * @param toRemove defines the skeleton to remove
  26109. * @returns the index where the skeleton was in the skeleton list
  26110. */
  26111. Scene.prototype.removeSkeleton = function (toRemove) {
  26112. var index = this.skeletons.indexOf(toRemove);
  26113. if (index !== -1) {
  26114. // Remove from the scene if found
  26115. this.skeletons.splice(index, 1);
  26116. }
  26117. return index;
  26118. };
  26119. /**
  26120. * Remove a morph target for the list of scene's morph targets
  26121. * @param toRemove defines the morph target to remove
  26122. * @returns the index where the morph target was in the morph target list
  26123. */
  26124. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26125. var index = this.morphTargetManagers.indexOf(toRemove);
  26126. if (index !== -1) {
  26127. // Remove from the scene if found
  26128. this.morphTargetManagers.splice(index, 1);
  26129. }
  26130. return index;
  26131. };
  26132. /**
  26133. * Remove a light for the list of scene's lights
  26134. * @param toRemove defines the light to remove
  26135. * @returns the index where the light was in the light list
  26136. */
  26137. Scene.prototype.removeLight = function (toRemove) {
  26138. var index = this.lights.indexOf(toRemove);
  26139. if (index !== -1) {
  26140. // Remove from meshes
  26141. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26142. var mesh = _a[_i];
  26143. mesh._removeLightSource(toRemove);
  26144. }
  26145. // Remove from the scene if mesh found
  26146. this.lights.splice(index, 1);
  26147. this.sortLightsByPriority();
  26148. }
  26149. this.onLightRemovedObservable.notifyObservers(toRemove);
  26150. return index;
  26151. };
  26152. /**
  26153. * Remove a camera for the list of scene's cameras
  26154. * @param toRemove defines the camera to remove
  26155. * @returns the index where the camera was in the camera list
  26156. */
  26157. Scene.prototype.removeCamera = function (toRemove) {
  26158. var index = this.cameras.indexOf(toRemove);
  26159. if (index !== -1) {
  26160. // Remove from the scene if mesh found
  26161. this.cameras.splice(index, 1);
  26162. }
  26163. // Remove from activeCameras
  26164. var index2 = this.activeCameras.indexOf(toRemove);
  26165. if (index2 !== -1) {
  26166. // Remove from the scene if mesh found
  26167. this.activeCameras.splice(index2, 1);
  26168. }
  26169. // Reset the activeCamera
  26170. if (this.activeCamera === toRemove) {
  26171. if (this.cameras.length > 0) {
  26172. this.activeCamera = this.cameras[0];
  26173. }
  26174. else {
  26175. this.activeCamera = null;
  26176. }
  26177. }
  26178. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26179. return index;
  26180. };
  26181. /**
  26182. * Remove a particle system for the list of scene's particle systems
  26183. * @param toRemove defines the particle system to remove
  26184. * @returns the index where the particle system was in the particle system list
  26185. */
  26186. Scene.prototype.removeParticleSystem = function (toRemove) {
  26187. var index = this.particleSystems.indexOf(toRemove);
  26188. if (index !== -1) {
  26189. this.particleSystems.splice(index, 1);
  26190. }
  26191. return index;
  26192. };
  26193. /**
  26194. * Remove a animation for the list of scene's animations
  26195. * @param toRemove defines the animation to remove
  26196. * @returns the index where the animation was in the animation list
  26197. */
  26198. Scene.prototype.removeAnimation = function (toRemove) {
  26199. var index = this.animations.indexOf(toRemove);
  26200. if (index !== -1) {
  26201. this.animations.splice(index, 1);
  26202. }
  26203. return index;
  26204. };
  26205. /**
  26206. * Removes the given animation group from this scene.
  26207. * @param toRemove The animation group to remove
  26208. * @returns The index of the removed animation group
  26209. */
  26210. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26211. var index = this.animationGroups.indexOf(toRemove);
  26212. if (index !== -1) {
  26213. this.animationGroups.splice(index, 1);
  26214. }
  26215. return index;
  26216. };
  26217. /**
  26218. * Removes the given multi-material from this scene.
  26219. * @param toRemove The multi-material to remove
  26220. * @returns The index of the removed multi-material
  26221. */
  26222. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26223. var index = this.multiMaterials.indexOf(toRemove);
  26224. if (index !== -1) {
  26225. this.multiMaterials.splice(index, 1);
  26226. }
  26227. return index;
  26228. };
  26229. /**
  26230. * Removes the given material from this scene.
  26231. * @param toRemove The material to remove
  26232. * @returns The index of the removed material
  26233. */
  26234. Scene.prototype.removeMaterial = function (toRemove) {
  26235. var index = this.materials.indexOf(toRemove);
  26236. if (index !== -1) {
  26237. this.materials.splice(index, 1);
  26238. }
  26239. return index;
  26240. };
  26241. /**
  26242. * Removes the given lens flare system from this scene.
  26243. * @param toRemove The lens flare system to remove
  26244. * @returns The index of the removed lens flare system
  26245. */
  26246. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26247. var index = this.lensFlareSystems.indexOf(toRemove);
  26248. if (index !== -1) {
  26249. this.lensFlareSystems.splice(index, 1);
  26250. }
  26251. return index;
  26252. };
  26253. /**
  26254. * Removes the given action manager from this scene.
  26255. * @param toRemove The action manager to remove
  26256. * @returns The index of the removed action manager
  26257. */
  26258. Scene.prototype.removeActionManager = function (toRemove) {
  26259. var index = this._actionManagers.indexOf(toRemove);
  26260. if (index !== -1) {
  26261. this._actionManagers.splice(index, 1);
  26262. }
  26263. return index;
  26264. };
  26265. /**
  26266. * Removes the given effect layer from this scene.
  26267. * @param toRemove defines the effect layer to remove
  26268. * @returns the index of the removed effect layer
  26269. */
  26270. Scene.prototype.removeEffectLayer = function (toRemove) {
  26271. var index = this.effectLayers.indexOf(toRemove);
  26272. if (index !== -1) {
  26273. this.effectLayers.splice(index, 1);
  26274. }
  26275. return index;
  26276. };
  26277. /**
  26278. * Removes the given texture from this scene.
  26279. * @param toRemove The texture to remove
  26280. * @returns The index of the removed texture
  26281. */
  26282. Scene.prototype.removeTexture = function (toRemove) {
  26283. var index = this.textures.indexOf(toRemove);
  26284. if (index !== -1) {
  26285. this.textures.splice(index, 1);
  26286. }
  26287. return index;
  26288. };
  26289. /**
  26290. * Adds the given light to this scene
  26291. * @param newLight The light to add
  26292. */
  26293. Scene.prototype.addLight = function (newLight) {
  26294. this.lights.push(newLight);
  26295. this.sortLightsByPriority();
  26296. // Add light to all meshes (To support if the light is removed and then readded)
  26297. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26298. var mesh = _a[_i];
  26299. if (mesh._lightSources.indexOf(newLight) === -1) {
  26300. mesh._lightSources.push(newLight);
  26301. mesh._resyncLightSources();
  26302. }
  26303. }
  26304. this.onNewLightAddedObservable.notifyObservers(newLight);
  26305. };
  26306. /**
  26307. * Sorts the list list based on light priorities
  26308. */
  26309. Scene.prototype.sortLightsByPriority = function () {
  26310. if (this.requireLightSorting) {
  26311. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26312. }
  26313. };
  26314. /**
  26315. * Adds the given camera to this scene
  26316. * @param newCamera The camera to add
  26317. */
  26318. Scene.prototype.addCamera = function (newCamera) {
  26319. this.cameras.push(newCamera);
  26320. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26321. };
  26322. /**
  26323. * Adds the given skeleton to this scene
  26324. * @param newSkeleton The skeleton to add
  26325. */
  26326. Scene.prototype.addSkeleton = function (newSkeleton) {
  26327. this.skeletons.push(newSkeleton);
  26328. };
  26329. /**
  26330. * Adds the given particle system to this scene
  26331. * @param newParticleSystem The particle system to add
  26332. */
  26333. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26334. this.particleSystems.push(newParticleSystem);
  26335. };
  26336. /**
  26337. * Adds the given animation to this scene
  26338. * @param newAnimation The animation to add
  26339. */
  26340. Scene.prototype.addAnimation = function (newAnimation) {
  26341. this.animations.push(newAnimation);
  26342. };
  26343. /**
  26344. * Adds the given animation group to this scene.
  26345. * @param newAnimationGroup The animation group to add
  26346. */
  26347. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26348. this.animationGroups.push(newAnimationGroup);
  26349. };
  26350. /**
  26351. * Adds the given multi-material to this scene
  26352. * @param newMultiMaterial The multi-material to add
  26353. */
  26354. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26355. this.multiMaterials.push(newMultiMaterial);
  26356. };
  26357. /**
  26358. * Adds the given material to this scene
  26359. * @param newMaterial The material to add
  26360. */
  26361. Scene.prototype.addMaterial = function (newMaterial) {
  26362. this.materials.push(newMaterial);
  26363. };
  26364. /**
  26365. * Adds the given morph target to this scene
  26366. * @param newMorphTargetManager The morph target to add
  26367. */
  26368. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26369. this.morphTargetManagers.push(newMorphTargetManager);
  26370. };
  26371. /**
  26372. * Adds the given geometry to this scene
  26373. * @param newGeometry The geometry to add
  26374. */
  26375. Scene.prototype.addGeometry = function (newGeometry) {
  26376. this._geometries.push(newGeometry);
  26377. };
  26378. /**
  26379. * Adds the given lens flare system to this scene
  26380. * @param newLensFlareSystem The lens flare system to add
  26381. */
  26382. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26383. this.lensFlareSystems.push(newLensFlareSystem);
  26384. };
  26385. /**
  26386. * Adds the given effect layer to this scene
  26387. * @param newEffectLayer defines the effect layer to add
  26388. */
  26389. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26390. this.effectLayers.push(newEffectLayer);
  26391. };
  26392. /**
  26393. * Adds the given action manager to this scene
  26394. * @param newActionManager The action manager to add
  26395. */
  26396. Scene.prototype.addActionManager = function (newActionManager) {
  26397. this._actionManagers.push(newActionManager);
  26398. };
  26399. /**
  26400. * Adds the given texture to this scene.
  26401. * @param newTexture The texture to add
  26402. */
  26403. Scene.prototype.addTexture = function (newTexture) {
  26404. this.textures.push(newTexture);
  26405. };
  26406. /**
  26407. * Switch active camera
  26408. * @param newCamera defines the new active camera
  26409. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26410. */
  26411. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26412. if (attachControl === void 0) { attachControl = true; }
  26413. var canvas = this._engine.getRenderingCanvas();
  26414. if (!canvas) {
  26415. return;
  26416. }
  26417. if (this.activeCamera) {
  26418. this.activeCamera.detachControl(canvas);
  26419. }
  26420. this.activeCamera = newCamera;
  26421. if (attachControl) {
  26422. newCamera.attachControl(canvas);
  26423. }
  26424. };
  26425. /**
  26426. * sets the active camera of the scene using its ID
  26427. * @param id defines the camera's ID
  26428. * @return the new active camera or null if none found.
  26429. */
  26430. Scene.prototype.setActiveCameraByID = function (id) {
  26431. var camera = this.getCameraByID(id);
  26432. if (camera) {
  26433. this.activeCamera = camera;
  26434. return camera;
  26435. }
  26436. return null;
  26437. };
  26438. /**
  26439. * sets the active camera of the scene using its name
  26440. * @param name defines the camera's name
  26441. * @returns the new active camera or null if none found.
  26442. */
  26443. Scene.prototype.setActiveCameraByName = function (name) {
  26444. var camera = this.getCameraByName(name);
  26445. if (camera) {
  26446. this.activeCamera = camera;
  26447. return camera;
  26448. }
  26449. return null;
  26450. };
  26451. /**
  26452. * get an animation group using its name
  26453. * @param name defines the material's name
  26454. * @return the animation group or null if none found.
  26455. */
  26456. Scene.prototype.getAnimationGroupByName = function (name) {
  26457. for (var index = 0; index < this.animationGroups.length; index++) {
  26458. if (this.animationGroups[index].name === name) {
  26459. return this.animationGroups[index];
  26460. }
  26461. }
  26462. return null;
  26463. };
  26464. /**
  26465. * get a material using its id
  26466. * @param id defines the material's ID
  26467. * @return the material or null if none found.
  26468. */
  26469. Scene.prototype.getMaterialByID = function (id) {
  26470. for (var index = 0; index < this.materials.length; index++) {
  26471. if (this.materials[index].id === id) {
  26472. return this.materials[index];
  26473. }
  26474. }
  26475. return null;
  26476. };
  26477. /**
  26478. * Gets a material using its name
  26479. * @param name defines the material's name
  26480. * @return the material or null if none found.
  26481. */
  26482. Scene.prototype.getMaterialByName = function (name) {
  26483. for (var index = 0; index < this.materials.length; index++) {
  26484. if (this.materials[index].name === name) {
  26485. return this.materials[index];
  26486. }
  26487. }
  26488. return null;
  26489. };
  26490. /**
  26491. * Gets a lens flare system using its name
  26492. * @param name defines the name to look for
  26493. * @returns the lens flare system or null if not found
  26494. */
  26495. Scene.prototype.getLensFlareSystemByName = function (name) {
  26496. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26497. if (this.lensFlareSystems[index].name === name) {
  26498. return this.lensFlareSystems[index];
  26499. }
  26500. }
  26501. return null;
  26502. };
  26503. /**
  26504. * Gets a lens flare system using its id
  26505. * @param id defines the id to look for
  26506. * @returns the lens flare system or null if not found
  26507. */
  26508. Scene.prototype.getLensFlareSystemByID = function (id) {
  26509. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26510. if (this.lensFlareSystems[index].id === id) {
  26511. return this.lensFlareSystems[index];
  26512. }
  26513. }
  26514. return null;
  26515. };
  26516. /**
  26517. * Gets a camera using its id
  26518. * @param id defines the id to look for
  26519. * @returns the camera or null if not found
  26520. */
  26521. Scene.prototype.getCameraByID = function (id) {
  26522. for (var index = 0; index < this.cameras.length; index++) {
  26523. if (this.cameras[index].id === id) {
  26524. return this.cameras[index];
  26525. }
  26526. }
  26527. return null;
  26528. };
  26529. /**
  26530. * Gets a camera using its unique id
  26531. * @param uniqueId defines the unique id to look for
  26532. * @returns the camera or null if not found
  26533. */
  26534. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26535. for (var index = 0; index < this.cameras.length; index++) {
  26536. if (this.cameras[index].uniqueId === uniqueId) {
  26537. return this.cameras[index];
  26538. }
  26539. }
  26540. return null;
  26541. };
  26542. /**
  26543. * Gets a camera using its name
  26544. * @param name defines the camera's name
  26545. * @return the camera or null if none found.
  26546. */
  26547. Scene.prototype.getCameraByName = function (name) {
  26548. for (var index = 0; index < this.cameras.length; index++) {
  26549. if (this.cameras[index].name === name) {
  26550. return this.cameras[index];
  26551. }
  26552. }
  26553. return null;
  26554. };
  26555. /**
  26556. * Gets a bone using its id
  26557. * @param id defines the bone's id
  26558. * @return the bone or null if not found
  26559. */
  26560. Scene.prototype.getBoneByID = function (id) {
  26561. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26562. var skeleton = this.skeletons[skeletonIndex];
  26563. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26564. if (skeleton.bones[boneIndex].id === id) {
  26565. return skeleton.bones[boneIndex];
  26566. }
  26567. }
  26568. }
  26569. return null;
  26570. };
  26571. /**
  26572. * Gets a bone using its id
  26573. * @param name defines the bone's name
  26574. * @return the bone or null if not found
  26575. */
  26576. Scene.prototype.getBoneByName = function (name) {
  26577. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26578. var skeleton = this.skeletons[skeletonIndex];
  26579. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26580. if (skeleton.bones[boneIndex].name === name) {
  26581. return skeleton.bones[boneIndex];
  26582. }
  26583. }
  26584. }
  26585. return null;
  26586. };
  26587. /**
  26588. * Gets a light node using its name
  26589. * @param name defines the the light's name
  26590. * @return the light or null if none found.
  26591. */
  26592. Scene.prototype.getLightByName = function (name) {
  26593. for (var index = 0; index < this.lights.length; index++) {
  26594. if (this.lights[index].name === name) {
  26595. return this.lights[index];
  26596. }
  26597. }
  26598. return null;
  26599. };
  26600. /**
  26601. * Gets a light node using its id
  26602. * @param id defines the light's id
  26603. * @return the light or null if none found.
  26604. */
  26605. Scene.prototype.getLightByID = function (id) {
  26606. for (var index = 0; index < this.lights.length; index++) {
  26607. if (this.lights[index].id === id) {
  26608. return this.lights[index];
  26609. }
  26610. }
  26611. return null;
  26612. };
  26613. /**
  26614. * Gets a light node using its scene-generated unique ID
  26615. * @param uniqueId defines the light's unique id
  26616. * @return the light or null if none found.
  26617. */
  26618. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26619. for (var index = 0; index < this.lights.length; index++) {
  26620. if (this.lights[index].uniqueId === uniqueId) {
  26621. return this.lights[index];
  26622. }
  26623. }
  26624. return null;
  26625. };
  26626. /**
  26627. * Gets a particle system by id
  26628. * @param id defines the particle system id
  26629. * @return the corresponding system or null if none found
  26630. */
  26631. Scene.prototype.getParticleSystemByID = function (id) {
  26632. for (var index = 0; index < this.particleSystems.length; index++) {
  26633. if (this.particleSystems[index].id === id) {
  26634. return this.particleSystems[index];
  26635. }
  26636. }
  26637. return null;
  26638. };
  26639. /**
  26640. * Gets a geometry using its ID
  26641. * @param id defines the geometry's id
  26642. * @return the geometry or null if none found.
  26643. */
  26644. Scene.prototype.getGeometryByID = function (id) {
  26645. for (var index = 0; index < this._geometries.length; index++) {
  26646. if (this._geometries[index].id === id) {
  26647. return this._geometries[index];
  26648. }
  26649. }
  26650. return null;
  26651. };
  26652. /**
  26653. * Add a new geometry to this scene
  26654. * @param geometry defines the geometry to be added to the scene.
  26655. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26656. * @return a boolean defining if the geometry was added or not
  26657. */
  26658. Scene.prototype.pushGeometry = function (geometry, force) {
  26659. if (!force && this.getGeometryByID(geometry.id)) {
  26660. return false;
  26661. }
  26662. this._geometries.push(geometry);
  26663. //notify the collision coordinator
  26664. if (this.collisionCoordinator) {
  26665. this.collisionCoordinator.onGeometryAdded(geometry);
  26666. }
  26667. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26668. return true;
  26669. };
  26670. /**
  26671. * Removes an existing geometry
  26672. * @param geometry defines the geometry to be removed from the scene
  26673. * @return a boolean defining if the geometry was removed or not
  26674. */
  26675. Scene.prototype.removeGeometry = function (geometry) {
  26676. var index = this._geometries.indexOf(geometry);
  26677. if (index > -1) {
  26678. this._geometries.splice(index, 1);
  26679. //notify the collision coordinator
  26680. if (this.collisionCoordinator) {
  26681. this.collisionCoordinator.onGeometryDeleted(geometry);
  26682. }
  26683. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26684. return true;
  26685. }
  26686. return false;
  26687. };
  26688. /**
  26689. * Gets the list of geometries attached to the scene
  26690. * @returns an array of Geometry
  26691. */
  26692. Scene.prototype.getGeometries = function () {
  26693. return this._geometries;
  26694. };
  26695. /**
  26696. * Gets the first added mesh found of a given ID
  26697. * @param id defines the id to search for
  26698. * @return the mesh found or null if not found at all
  26699. */
  26700. Scene.prototype.getMeshByID = function (id) {
  26701. for (var index = 0; index < this.meshes.length; index++) {
  26702. if (this.meshes[index].id === id) {
  26703. return this.meshes[index];
  26704. }
  26705. }
  26706. return null;
  26707. };
  26708. /**
  26709. * Gets a list of meshes using their id
  26710. * @param id defines the id to search for
  26711. * @returns a list of meshes
  26712. */
  26713. Scene.prototype.getMeshesByID = function (id) {
  26714. return this.meshes.filter(function (m) {
  26715. return m.id === id;
  26716. });
  26717. };
  26718. /**
  26719. * Gets the first added transform node found of a given ID
  26720. * @param id defines the id to search for
  26721. * @return the found transform node or null if not found at all.
  26722. */
  26723. Scene.prototype.getTransformNodeByID = function (id) {
  26724. for (var index = 0; index < this.transformNodes.length; index++) {
  26725. if (this.transformNodes[index].id === id) {
  26726. return this.transformNodes[index];
  26727. }
  26728. }
  26729. return null;
  26730. };
  26731. /**
  26732. * Gets a list of transform nodes using their id
  26733. * @param id defines the id to search for
  26734. * @returns a list of transform nodes
  26735. */
  26736. Scene.prototype.getTransformNodesByID = function (id) {
  26737. return this.transformNodes.filter(function (m) {
  26738. return m.id === id;
  26739. });
  26740. };
  26741. /**
  26742. * Gets a mesh with its auto-generated unique id
  26743. * @param uniqueId defines the unique id to search for
  26744. * @return the found mesh or null if not found at all.
  26745. */
  26746. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26747. for (var index = 0; index < this.meshes.length; index++) {
  26748. if (this.meshes[index].uniqueId === uniqueId) {
  26749. return this.meshes[index];
  26750. }
  26751. }
  26752. return null;
  26753. };
  26754. /**
  26755. * Gets a the last added mesh using a given id
  26756. * @param id defines the id to search for
  26757. * @return the found mesh or null if not found at all.
  26758. */
  26759. Scene.prototype.getLastMeshByID = function (id) {
  26760. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26761. if (this.meshes[index].id === id) {
  26762. return this.meshes[index];
  26763. }
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26769. * @param id defines the id to search for
  26770. * @return the found node or null if not found at all
  26771. */
  26772. Scene.prototype.getLastEntryByID = function (id) {
  26773. var index;
  26774. for (index = this.meshes.length - 1; index >= 0; index--) {
  26775. if (this.meshes[index].id === id) {
  26776. return this.meshes[index];
  26777. }
  26778. }
  26779. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26780. if (this.transformNodes[index].id === id) {
  26781. return this.transformNodes[index];
  26782. }
  26783. }
  26784. for (index = this.cameras.length - 1; index >= 0; index--) {
  26785. if (this.cameras[index].id === id) {
  26786. return this.cameras[index];
  26787. }
  26788. }
  26789. for (index = this.lights.length - 1; index >= 0; index--) {
  26790. if (this.lights[index].id === id) {
  26791. return this.lights[index];
  26792. }
  26793. }
  26794. return null;
  26795. };
  26796. /**
  26797. * Gets a node (Mesh, Camera, Light) using a given id
  26798. * @param id defines the id to search for
  26799. * @return the found node or null if not found at all
  26800. */
  26801. Scene.prototype.getNodeByID = function (id) {
  26802. var mesh = this.getMeshByID(id);
  26803. if (mesh) {
  26804. return mesh;
  26805. }
  26806. var light = this.getLightByID(id);
  26807. if (light) {
  26808. return light;
  26809. }
  26810. var camera = this.getCameraByID(id);
  26811. if (camera) {
  26812. return camera;
  26813. }
  26814. var bone = this.getBoneByID(id);
  26815. return bone;
  26816. };
  26817. /**
  26818. * Gets a node (Mesh, Camera, Light) using a given name
  26819. * @param name defines the name to search for
  26820. * @return the found node or null if not found at all.
  26821. */
  26822. Scene.prototype.getNodeByName = function (name) {
  26823. var mesh = this.getMeshByName(name);
  26824. if (mesh) {
  26825. return mesh;
  26826. }
  26827. var light = this.getLightByName(name);
  26828. if (light) {
  26829. return light;
  26830. }
  26831. var camera = this.getCameraByName(name);
  26832. if (camera) {
  26833. return camera;
  26834. }
  26835. var bone = this.getBoneByName(name);
  26836. return bone;
  26837. };
  26838. /**
  26839. * Gets a mesh using a given name
  26840. * @param name defines the name to search for
  26841. * @return the found mesh or null if not found at all.
  26842. */
  26843. Scene.prototype.getMeshByName = function (name) {
  26844. for (var index = 0; index < this.meshes.length; index++) {
  26845. if (this.meshes[index].name === name) {
  26846. return this.meshes[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a transform node using a given name
  26853. * @param name defines the name to search for
  26854. * @return the found transform node or null if not found at all.
  26855. */
  26856. Scene.prototype.getTransformNodeByName = function (name) {
  26857. for (var index = 0; index < this.transformNodes.length; index++) {
  26858. if (this.transformNodes[index].name === name) {
  26859. return this.transformNodes[index];
  26860. }
  26861. }
  26862. return null;
  26863. };
  26864. /**
  26865. * Gets a sound using a given name
  26866. * @param name defines the name to search for
  26867. * @return the found sound or null if not found at all.
  26868. */
  26869. Scene.prototype.getSoundByName = function (name) {
  26870. var index;
  26871. if (BABYLON.AudioEngine) {
  26872. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26873. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26874. return this.mainSoundTrack.soundCollection[index];
  26875. }
  26876. }
  26877. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26878. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26879. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26880. return this.soundTracks[sdIndex].soundCollection[index];
  26881. }
  26882. }
  26883. }
  26884. }
  26885. return null;
  26886. };
  26887. /**
  26888. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26889. * @param id defines the id to search for
  26890. * @return the found skeleton or null if not found at all.
  26891. */
  26892. Scene.prototype.getLastSkeletonByID = function (id) {
  26893. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26894. if (this.skeletons[index].id === id) {
  26895. return this.skeletons[index];
  26896. }
  26897. }
  26898. return null;
  26899. };
  26900. /**
  26901. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26902. * @param id defines the id to search for
  26903. * @return the found skeleton or null if not found at all.
  26904. */
  26905. Scene.prototype.getSkeletonById = function (id) {
  26906. for (var index = 0; index < this.skeletons.length; index++) {
  26907. if (this.skeletons[index].id === id) {
  26908. return this.skeletons[index];
  26909. }
  26910. }
  26911. return null;
  26912. };
  26913. /**
  26914. * Gets a skeleton using a given name
  26915. * @param name defines the name to search for
  26916. * @return the found skeleton or null if not found at all.
  26917. */
  26918. Scene.prototype.getSkeletonByName = function (name) {
  26919. for (var index = 0; index < this.skeletons.length; index++) {
  26920. if (this.skeletons[index].name === name) {
  26921. return this.skeletons[index];
  26922. }
  26923. }
  26924. return null;
  26925. };
  26926. /**
  26927. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26928. * @param id defines the id to search for
  26929. * @return the found morph target manager or null if not found at all.
  26930. */
  26931. Scene.prototype.getMorphTargetManagerById = function (id) {
  26932. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26933. if (this.morphTargetManagers[index].uniqueId === id) {
  26934. return this.morphTargetManagers[index];
  26935. }
  26936. }
  26937. return null;
  26938. };
  26939. /**
  26940. * Gets a boolean indicating if the given mesh is active
  26941. * @param mesh defines the mesh to look for
  26942. * @returns true if the mesh is in the active list
  26943. */
  26944. Scene.prototype.isActiveMesh = function (mesh) {
  26945. return (this._activeMeshes.indexOf(mesh) !== -1);
  26946. };
  26947. /**
  26948. * Return a the first highlight layer of the scene with a given name.
  26949. * @param name The name of the highlight layer to look for.
  26950. * @return The highlight layer if found otherwise null.
  26951. */
  26952. Scene.prototype.getHighlightLayerByName = function (name) {
  26953. for (var index = 0; index < this.effectLayers.length; index++) {
  26954. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26955. return this.effectLayers[index];
  26956. }
  26957. }
  26958. return null;
  26959. };
  26960. /**
  26961. * Return a the first highlight layer of the scene with a given name.
  26962. * @param name The name of the highlight layer to look for.
  26963. * @return The highlight layer if found otherwise null.
  26964. */
  26965. Scene.prototype.getGlowLayerByName = function (name) {
  26966. for (var index = 0; index < this.effectLayers.length; index++) {
  26967. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26968. return this.effectLayers[index];
  26969. }
  26970. }
  26971. return null;
  26972. };
  26973. Object.defineProperty(Scene.prototype, "uid", {
  26974. /**
  26975. * Return a unique id as a string which can serve as an identifier for the scene
  26976. */
  26977. get: function () {
  26978. if (!this._uid) {
  26979. this._uid = BABYLON.Tools.RandomId();
  26980. }
  26981. return this._uid;
  26982. },
  26983. enumerable: true,
  26984. configurable: true
  26985. });
  26986. /**
  26987. * Add an externaly attached data from its key.
  26988. * This method call will fail and return false, if such key already exists.
  26989. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26990. * @param key the unique key that identifies the data
  26991. * @param data the data object to associate to the key for this Engine instance
  26992. * @return true if no such key were already present and the data was added successfully, false otherwise
  26993. */
  26994. Scene.prototype.addExternalData = function (key, data) {
  26995. if (!this._externalData) {
  26996. this._externalData = new BABYLON.StringDictionary();
  26997. }
  26998. return this._externalData.add(key, data);
  26999. };
  27000. /**
  27001. * Get an externaly attached data from its key
  27002. * @param key the unique key that identifies the data
  27003. * @return the associated data, if present (can be null), or undefined if not present
  27004. */
  27005. Scene.prototype.getExternalData = function (key) {
  27006. if (!this._externalData) {
  27007. return null;
  27008. }
  27009. return this._externalData.get(key);
  27010. };
  27011. /**
  27012. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27013. * @param key the unique key that identifies the data
  27014. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27015. * @return the associated data, can be null if the factory returned null.
  27016. */
  27017. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27018. if (!this._externalData) {
  27019. this._externalData = new BABYLON.StringDictionary();
  27020. }
  27021. return this._externalData.getOrAddWithFactory(key, factory);
  27022. };
  27023. /**
  27024. * Remove an externaly attached data from the Engine instance
  27025. * @param key the unique key that identifies the data
  27026. * @return true if the data was successfully removed, false if it doesn't exist
  27027. */
  27028. Scene.prototype.removeExternalData = function (key) {
  27029. return this._externalData.remove(key);
  27030. };
  27031. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27032. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27033. if (mesh.showSubMeshesBoundingBox) {
  27034. var boundingInfo = subMesh.getBoundingInfo();
  27035. if (boundingInfo !== null && boundingInfo !== undefined) {
  27036. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27037. }
  27038. }
  27039. var material = subMesh.getMaterial();
  27040. if (material !== null && material !== undefined) {
  27041. // Render targets
  27042. if (material.getRenderTargetTextures !== undefined) {
  27043. if (this._processedMaterials.indexOf(material) === -1) {
  27044. this._processedMaterials.push(material);
  27045. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27046. }
  27047. }
  27048. // Dispatch
  27049. this._activeIndices.addCount(subMesh.indexCount, false);
  27050. this._renderingManager.dispatch(subMesh, mesh, material);
  27051. }
  27052. }
  27053. };
  27054. /**
  27055. * Clear the processed materials smart array preventing retention point in material dispose.
  27056. */
  27057. Scene.prototype.freeProcessedMaterials = function () {
  27058. this._processedMaterials.dispose();
  27059. };
  27060. /**
  27061. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27062. */
  27063. Scene.prototype.freeActiveMeshes = function () {
  27064. this._activeMeshes.dispose();
  27065. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27066. this.activeCamera._activeMeshes.dispose();
  27067. }
  27068. if (this.activeCameras) {
  27069. for (var i = 0; i < this.activeCameras.length; i++) {
  27070. var activeCamera = this.activeCameras[i];
  27071. if (activeCamera && activeCamera._activeMeshes) {
  27072. activeCamera._activeMeshes.dispose();
  27073. }
  27074. }
  27075. }
  27076. };
  27077. /**
  27078. * Clear the info related to rendering groups preventing retention points during dispose.
  27079. */
  27080. Scene.prototype.freeRenderingGroups = function () {
  27081. if (this._renderingManager) {
  27082. this._renderingManager.freeRenderingGroups();
  27083. }
  27084. if (this.textures) {
  27085. for (var i = 0; i < this.textures.length; i++) {
  27086. var texture = this.textures[i];
  27087. if (texture && texture.renderList) {
  27088. texture.freeRenderingGroups();
  27089. }
  27090. }
  27091. }
  27092. };
  27093. /** @hidden */
  27094. Scene.prototype._isInIntermediateRendering = function () {
  27095. return this._intermediateRendering;
  27096. };
  27097. /**
  27098. * Defines the current active mesh candidate provider
  27099. * @param provider defines the provider to use
  27100. */
  27101. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27102. this._activeMeshCandidateProvider = provider;
  27103. };
  27104. /**
  27105. * Gets the current active mesh candidate provider
  27106. * @returns the current active mesh candidate provider
  27107. */
  27108. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27109. return this._activeMeshCandidateProvider;
  27110. };
  27111. /**
  27112. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27113. * @returns the current scene
  27114. */
  27115. Scene.prototype.freezeActiveMeshes = function () {
  27116. if (!this.activeCamera) {
  27117. return this;
  27118. }
  27119. if (!this._frustumPlanes) {
  27120. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27121. }
  27122. this._evaluateActiveMeshes();
  27123. this._activeMeshesFrozen = true;
  27124. return this;
  27125. };
  27126. /**
  27127. * Use this function to restart evaluating active meshes on every frame
  27128. * @returns the current scene
  27129. */
  27130. Scene.prototype.unfreezeActiveMeshes = function () {
  27131. this._activeMeshesFrozen = false;
  27132. return this;
  27133. };
  27134. Scene.prototype._evaluateActiveMeshes = function () {
  27135. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27136. return;
  27137. }
  27138. if (!this.activeCamera) {
  27139. return;
  27140. }
  27141. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27142. this.activeCamera._activeMeshes.reset();
  27143. this._activeMeshes.reset();
  27144. this._renderingManager.reset();
  27145. this._processedMaterials.reset();
  27146. this._activeParticleSystems.reset();
  27147. this._activeSkeletons.reset();
  27148. this._softwareSkinnedMeshes.reset();
  27149. if (this._boundingBoxRenderer) {
  27150. this._boundingBoxRenderer.reset();
  27151. }
  27152. // Meshes
  27153. var meshes;
  27154. var len;
  27155. var checkIsEnabled = true;
  27156. // Determine mesh candidates
  27157. if (this._activeMeshCandidateProvider !== undefined) {
  27158. // Use _activeMeshCandidateProvider
  27159. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27160. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27161. if (meshes !== undefined) {
  27162. len = meshes.length;
  27163. }
  27164. else {
  27165. len = 0;
  27166. }
  27167. }
  27168. else if (this._selectionOctree !== undefined) {
  27169. // Octree
  27170. var selection = this._selectionOctree.select(this._frustumPlanes);
  27171. meshes = selection.data;
  27172. len = selection.length;
  27173. }
  27174. else {
  27175. // Full scene traversal
  27176. len = this.meshes.length;
  27177. meshes = this.meshes;
  27178. }
  27179. // Check each mesh
  27180. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27181. mesh = meshes[meshIndex];
  27182. if (mesh.isBlocked) {
  27183. continue;
  27184. }
  27185. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27186. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27187. continue;
  27188. }
  27189. mesh.computeWorldMatrix();
  27190. // Intersections
  27191. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27192. this._meshesForIntersections.pushNoDuplicate(mesh);
  27193. }
  27194. // Switch to current LOD
  27195. meshLOD = mesh.getLOD(this.activeCamera);
  27196. if (meshLOD === undefined || meshLOD === null) {
  27197. continue;
  27198. }
  27199. mesh._preActivate();
  27200. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27201. this._activeMeshes.push(mesh);
  27202. this.activeCamera._activeMeshes.push(mesh);
  27203. mesh._activate(this._renderId);
  27204. if (meshLOD !== mesh) {
  27205. meshLOD._activate(this._renderId);
  27206. }
  27207. this._activeMesh(mesh, meshLOD);
  27208. }
  27209. }
  27210. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27211. // Particle systems
  27212. if (this.particlesEnabled) {
  27213. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27214. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27215. var particleSystem = this.particleSystems[particleIndex];
  27216. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27217. continue;
  27218. }
  27219. var emitter = particleSystem.emitter;
  27220. if (!emitter.position || emitter.isEnabled()) {
  27221. this._activeParticleSystems.push(particleSystem);
  27222. particleSystem.animate();
  27223. this._renderingManager.dispatchParticles(particleSystem);
  27224. }
  27225. }
  27226. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27227. }
  27228. };
  27229. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27230. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27231. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27232. mesh.skeleton.prepare();
  27233. }
  27234. if (!mesh.computeBonesUsingShaders) {
  27235. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27236. }
  27237. }
  27238. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27239. var boundingInfo = sourceMesh.getBoundingInfo();
  27240. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27241. }
  27242. if (mesh !== undefined && mesh !== null
  27243. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27244. // Submeshes Octrees
  27245. var len;
  27246. var subMeshes;
  27247. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27248. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27249. len = intersections.length;
  27250. subMeshes = intersections.data;
  27251. }
  27252. else {
  27253. subMeshes = mesh.subMeshes;
  27254. len = subMeshes.length;
  27255. }
  27256. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27257. subMesh = subMeshes[subIndex];
  27258. this._evaluateSubMesh(subMesh, mesh);
  27259. }
  27260. }
  27261. };
  27262. /**
  27263. * Update the transform matrix to update from the current active camera
  27264. * @param force defines a boolean used to force the update even if cache is up to date
  27265. */
  27266. Scene.prototype.updateTransformMatrix = function (force) {
  27267. if (!this.activeCamera) {
  27268. return;
  27269. }
  27270. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27271. };
  27272. /**
  27273. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27274. * @param alternateCamera defines the camera to use
  27275. */
  27276. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27277. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27278. };
  27279. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27280. if (camera && camera._skipRendering) {
  27281. return;
  27282. }
  27283. var engine = this._engine;
  27284. this.activeCamera = camera;
  27285. if (!this.activeCamera)
  27286. throw new Error("Active camera not set");
  27287. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27288. // Viewport
  27289. engine.setViewport(this.activeCamera.viewport);
  27290. // Camera
  27291. this.resetCachedMaterial();
  27292. this._renderId++;
  27293. this.updateTransformMatrix();
  27294. if (camera._alternateCamera) {
  27295. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27296. this._alternateRendering = true;
  27297. }
  27298. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27299. // Meshes
  27300. this._evaluateActiveMeshes();
  27301. // Software skinning
  27302. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27303. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27304. mesh.applySkeleton(mesh.skeleton);
  27305. }
  27306. // Render targets
  27307. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27308. var needsRestoreFrameBuffer = false;
  27309. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27310. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27311. }
  27312. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27313. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27314. }
  27315. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27316. this._intermediateRendering = true;
  27317. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27318. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27319. var renderTarget = this._renderTargets.data[renderIndex];
  27320. if (renderTarget._shouldRender()) {
  27321. this._renderId++;
  27322. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27323. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27324. }
  27325. }
  27326. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27327. this._intermediateRendering = false;
  27328. this._renderId++;
  27329. needsRestoreFrameBuffer = true; // Restore back buffer
  27330. }
  27331. // Render EffecttLayer Texture
  27332. var stencilState = this._engine.getStencilBuffer();
  27333. var renderEffects = false;
  27334. var needStencil = false;
  27335. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27336. this._intermediateRendering = true;
  27337. for (var i = 0; i < this.effectLayers.length; i++) {
  27338. var effectLayer = this.effectLayers[i];
  27339. if (effectLayer.shouldRender() &&
  27340. (!effectLayer.camera ||
  27341. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27342. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27343. renderEffects = true;
  27344. needStencil = needStencil || effectLayer.needStencil();
  27345. var renderTarget = effectLayer._mainTexture;
  27346. if (renderTarget._shouldRender()) {
  27347. this._renderId++;
  27348. renderTarget.render(false, false);
  27349. needsRestoreFrameBuffer = true;
  27350. }
  27351. }
  27352. }
  27353. this._intermediateRendering = false;
  27354. this._renderId++;
  27355. }
  27356. if (needsRestoreFrameBuffer) {
  27357. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27358. }
  27359. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27360. // Prepare Frame
  27361. this.postProcessManager._prepareFrame();
  27362. // Backgrounds
  27363. var layerIndex;
  27364. var layer;
  27365. if (this.layers.length) {
  27366. engine.setDepthBuffer(false);
  27367. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27368. layer = this.layers[layerIndex];
  27369. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27370. layer.render();
  27371. }
  27372. }
  27373. engine.setDepthBuffer(true);
  27374. }
  27375. // Activate effect Layer stencil
  27376. if (needStencil) {
  27377. this._engine.setStencilBuffer(true);
  27378. }
  27379. // Render
  27380. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27381. this._renderingManager.render(null, null, true, true);
  27382. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27383. // Restore effect Layer stencil
  27384. if (needStencil) {
  27385. this._engine.setStencilBuffer(stencilState);
  27386. }
  27387. // Bounding boxes
  27388. if (this._boundingBoxRenderer) {
  27389. this._boundingBoxRenderer.render();
  27390. }
  27391. // Lens flares
  27392. if (this.lensFlaresEnabled) {
  27393. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27394. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27395. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27396. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27397. lensFlareSystem.render();
  27398. }
  27399. }
  27400. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27401. }
  27402. // Effect Layer
  27403. if (renderEffects) {
  27404. engine.setDepthBuffer(false);
  27405. for (var i = 0; i < this.effectLayers.length; i++) {
  27406. if (this.effectLayers[i].shouldRender()) {
  27407. this.effectLayers[i].render();
  27408. }
  27409. }
  27410. engine.setDepthBuffer(true);
  27411. }
  27412. // Foregrounds
  27413. if (this.layers.length) {
  27414. engine.setDepthBuffer(false);
  27415. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27416. layer = this.layers[layerIndex];
  27417. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27418. layer.render();
  27419. }
  27420. }
  27421. engine.setDepthBuffer(true);
  27422. }
  27423. // Finalize frame
  27424. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27425. // Reset some special arrays
  27426. this._renderTargets.reset();
  27427. this._alternateRendering = false;
  27428. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27429. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27430. };
  27431. Scene.prototype._processSubCameras = function (camera) {
  27432. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27433. this._renderForCamera(camera);
  27434. return;
  27435. }
  27436. // rig cameras
  27437. for (var index = 0; index < camera._rigCameras.length; index++) {
  27438. this._renderForCamera(camera._rigCameras[index], camera);
  27439. }
  27440. this.activeCamera = camera;
  27441. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27442. };
  27443. Scene.prototype._checkIntersections = function () {
  27444. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27445. var sourceMesh = this._meshesForIntersections.data[index];
  27446. if (!sourceMesh.actionManager) {
  27447. continue;
  27448. }
  27449. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27450. var action = sourceMesh.actionManager.actions[actionIndex];
  27451. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27452. var parameters = action.getTriggerParameter();
  27453. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27454. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27455. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27456. if (areIntersecting && currentIntersectionInProgress === -1) {
  27457. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27458. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27459. sourceMesh._intersectionsInProgress.push(otherMesh);
  27460. }
  27461. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27462. sourceMesh._intersectionsInProgress.push(otherMesh);
  27463. }
  27464. }
  27465. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27466. //They intersected, and now they don't.
  27467. //is this trigger an exit trigger? execute an event.
  27468. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27469. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27470. }
  27471. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27472. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27473. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27474. return otherMesh === parameterMesh;
  27475. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27476. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27477. }
  27478. }
  27479. }
  27480. }
  27481. }
  27482. };
  27483. /**
  27484. * Render the scene
  27485. */
  27486. Scene.prototype.render = function () {
  27487. if (this.isDisposed) {
  27488. return;
  27489. }
  27490. this._activeParticles.fetchNewFrame();
  27491. this._totalVertices.fetchNewFrame();
  27492. this._activeIndices.fetchNewFrame();
  27493. this._activeBones.fetchNewFrame();
  27494. this._meshesForIntersections.reset();
  27495. this.resetCachedMaterial();
  27496. this.onBeforeAnimationsObservable.notifyObservers(this);
  27497. // Actions
  27498. if (this.actionManager) {
  27499. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27500. }
  27501. //Simplification Queue
  27502. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27503. this.simplificationQueue.executeNext();
  27504. }
  27505. if (this._engine.isDeterministicLockStep()) {
  27506. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27507. var defaultFPS = (60.0 / 1000.0);
  27508. var defaultFrameTime = 1000 / 60; // frame time in MS
  27509. if (this._physicsEngine) {
  27510. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27511. }
  27512. var stepsTaken = 0;
  27513. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27514. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27515. internalSteps = Math.min(internalSteps, maxSubSteps);
  27516. do {
  27517. this.onBeforeStepObservable.notifyObservers(this);
  27518. // Animations
  27519. this._animationRatio = defaultFrameTime * defaultFPS;
  27520. this._animate();
  27521. this.onAfterAnimationsObservable.notifyObservers(this);
  27522. // Physics
  27523. if (this._physicsEngine) {
  27524. this.onBeforePhysicsObservable.notifyObservers(this);
  27525. this._physicsEngine._step(defaultFrameTime / 1000);
  27526. this.onAfterPhysicsObservable.notifyObservers(this);
  27527. }
  27528. this.onAfterStepObservable.notifyObservers(this);
  27529. this._currentStepId++;
  27530. stepsTaken++;
  27531. deltaTime -= defaultFrameTime;
  27532. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27533. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27534. }
  27535. else {
  27536. // Animations
  27537. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27538. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27539. this._animate();
  27540. this.onAfterAnimationsObservable.notifyObservers(this);
  27541. // Physics
  27542. if (this._physicsEngine) {
  27543. this.onBeforePhysicsObservable.notifyObservers(this);
  27544. this._physicsEngine._step(deltaTime / 1000.0);
  27545. this.onAfterPhysicsObservable.notifyObservers(this);
  27546. }
  27547. }
  27548. // update gamepad manager
  27549. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27550. this._gamepadManager._checkGamepadsStatus();
  27551. }
  27552. // Update Cameras
  27553. if (this.activeCameras.length > 0) {
  27554. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27555. var camera = this.activeCameras[cameraIndex];
  27556. camera.update();
  27557. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27558. // rig cameras
  27559. for (var index = 0; index < camera._rigCameras.length; index++) {
  27560. camera._rigCameras[index].update();
  27561. }
  27562. }
  27563. }
  27564. }
  27565. else if (this.activeCamera) {
  27566. this.activeCamera.update();
  27567. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27568. // rig cameras
  27569. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27570. this.activeCamera._rigCameras[index].update();
  27571. }
  27572. }
  27573. }
  27574. // Before render
  27575. this.onBeforeRenderObservable.notifyObservers(this);
  27576. // Customs render targets
  27577. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27578. var engine = this.getEngine();
  27579. var currentActiveCamera = this.activeCamera;
  27580. if (this.renderTargetsEnabled) {
  27581. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27582. this._intermediateRendering = true;
  27583. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27584. var renderTarget = this.customRenderTargets[customIndex];
  27585. if (renderTarget._shouldRender()) {
  27586. this._renderId++;
  27587. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27588. if (!this.activeCamera)
  27589. throw new Error("Active camera not set");
  27590. // Viewport
  27591. engine.setViewport(this.activeCamera.viewport);
  27592. // Camera
  27593. this.updateTransformMatrix();
  27594. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27595. }
  27596. }
  27597. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27598. this._intermediateRendering = false;
  27599. this._renderId++;
  27600. }
  27601. // Restore back buffer
  27602. if (this.customRenderTargets.length > 0) {
  27603. engine.restoreDefaultFramebuffer();
  27604. }
  27605. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27606. this.activeCamera = currentActiveCamera;
  27607. // Procedural textures
  27608. if (this.proceduralTexturesEnabled) {
  27609. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27610. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27611. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27612. if (proceduralTexture._shouldRender()) {
  27613. proceduralTexture.render();
  27614. }
  27615. }
  27616. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27617. }
  27618. // Clear
  27619. if (this.autoClearDepthAndStencil || this.autoClear) {
  27620. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27621. }
  27622. // Shadows
  27623. if (this.shadowsEnabled) {
  27624. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27625. var light = this.lights[lightIndex];
  27626. var shadowGenerator = light.getShadowGenerator();
  27627. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27628. var shadowMap = (shadowGenerator.getShadowMap());
  27629. if (this.textures.indexOf(shadowMap) !== -1) {
  27630. this._renderTargets.push(shadowMap);
  27631. }
  27632. }
  27633. }
  27634. }
  27635. // Depth renderer
  27636. for (var key in this._depthRenderer) {
  27637. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27638. }
  27639. // Geometry renderer
  27640. if (this._geometryBufferRenderer) {
  27641. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27642. }
  27643. // RenderPipeline
  27644. if (this._postProcessRenderPipelineManager) {
  27645. this._postProcessRenderPipelineManager.update();
  27646. }
  27647. // Multi-cameras?
  27648. if (this.activeCameras.length > 0) {
  27649. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27650. if (cameraIndex > 0) {
  27651. this._engine.clear(null, false, true, true);
  27652. }
  27653. this._processSubCameras(this.activeCameras[cameraIndex]);
  27654. }
  27655. }
  27656. else {
  27657. if (!this.activeCamera) {
  27658. throw new Error("No camera defined");
  27659. }
  27660. this._processSubCameras(this.activeCamera);
  27661. }
  27662. // Intersection checks
  27663. this._checkIntersections();
  27664. // Update the audio listener attached to the camera
  27665. if (BABYLON.AudioEngine) {
  27666. this._updateAudioParameters();
  27667. }
  27668. // After render
  27669. if (this.afterRender) {
  27670. this.afterRender();
  27671. }
  27672. this.onAfterRenderObservable.notifyObservers(this);
  27673. // Cleaning
  27674. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27675. var data = this._toBeDisposed.data[index];
  27676. if (data) {
  27677. data.dispose();
  27678. }
  27679. this._toBeDisposed[index] = null;
  27680. }
  27681. this._toBeDisposed.reset();
  27682. if (this.dumpNextRenderTargets) {
  27683. this.dumpNextRenderTargets = false;
  27684. }
  27685. this._activeBones.addCount(0, true);
  27686. this._activeIndices.addCount(0, true);
  27687. this._activeParticles.addCount(0, true);
  27688. };
  27689. Scene.prototype._updateAudioParameters = function () {
  27690. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27691. return;
  27692. }
  27693. var listeningCamera;
  27694. var audioEngine = BABYLON.Engine.audioEngine;
  27695. if (this.activeCameras.length > 0) {
  27696. listeningCamera = this.activeCameras[0];
  27697. }
  27698. else {
  27699. listeningCamera = this.activeCamera;
  27700. }
  27701. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27702. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27703. // for VR cameras
  27704. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27705. listeningCamera = listeningCamera.rigCameras[0];
  27706. }
  27707. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27708. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27709. cameraDirection.normalize();
  27710. // To avoid some errors on GearVR
  27711. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27712. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27713. }
  27714. var i;
  27715. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27716. var sound = this.mainSoundTrack.soundCollection[i];
  27717. if (sound.useCustomAttenuation) {
  27718. sound.updateDistanceFromListener();
  27719. }
  27720. }
  27721. for (i = 0; i < this.soundTracks.length; i++) {
  27722. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27723. sound = this.soundTracks[i].soundCollection[j];
  27724. if (sound.useCustomAttenuation) {
  27725. sound.updateDistanceFromListener();
  27726. }
  27727. }
  27728. }
  27729. }
  27730. };
  27731. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27732. // Audio
  27733. /**
  27734. * Gets or sets if audio support is enabled
  27735. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27736. */
  27737. get: function () {
  27738. return this._audioEnabled;
  27739. },
  27740. set: function (value) {
  27741. this._audioEnabled = value;
  27742. if (BABYLON.AudioEngine) {
  27743. if (this._audioEnabled) {
  27744. this._enableAudio();
  27745. }
  27746. else {
  27747. this._disableAudio();
  27748. }
  27749. }
  27750. },
  27751. enumerable: true,
  27752. configurable: true
  27753. });
  27754. Scene.prototype._disableAudio = function () {
  27755. var i;
  27756. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27757. this.mainSoundTrack.soundCollection[i].pause();
  27758. }
  27759. for (i = 0; i < this.soundTracks.length; i++) {
  27760. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27761. this.soundTracks[i].soundCollection[j].pause();
  27762. }
  27763. }
  27764. };
  27765. Scene.prototype._enableAudio = function () {
  27766. var i;
  27767. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27768. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27769. this.mainSoundTrack.soundCollection[i].play();
  27770. }
  27771. }
  27772. for (i = 0; i < this.soundTracks.length; i++) {
  27773. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27774. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27775. this.soundTracks[i].soundCollection[j].play();
  27776. }
  27777. }
  27778. }
  27779. };
  27780. Object.defineProperty(Scene.prototype, "headphone", {
  27781. /**
  27782. * Gets or sets if audio will be output to headphones
  27783. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27784. */
  27785. get: function () {
  27786. return this._headphone;
  27787. },
  27788. set: function (value) {
  27789. this._headphone = value;
  27790. if (BABYLON.AudioEngine) {
  27791. if (this._headphone) {
  27792. this._switchAudioModeForHeadphones();
  27793. }
  27794. else {
  27795. this._switchAudioModeForNormalSpeakers();
  27796. }
  27797. }
  27798. },
  27799. enumerable: true,
  27800. configurable: true
  27801. });
  27802. Scene.prototype._switchAudioModeForHeadphones = function () {
  27803. this.mainSoundTrack.switchPanningModelToHRTF();
  27804. for (var i = 0; i < this.soundTracks.length; i++) {
  27805. this.soundTracks[i].switchPanningModelToHRTF();
  27806. }
  27807. };
  27808. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27809. this.mainSoundTrack.switchPanningModelToEqualPower();
  27810. for (var i = 0; i < this.soundTracks.length; i++) {
  27811. this.soundTracks[i].switchPanningModelToEqualPower();
  27812. }
  27813. };
  27814. /**
  27815. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27816. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27817. * @returns the created depth renderer
  27818. */
  27819. Scene.prototype.enableDepthRenderer = function (camera) {
  27820. camera = camera || this.activeCamera;
  27821. if (!camera) {
  27822. throw "No camera available to enable depth renderer";
  27823. }
  27824. if (!this._depthRenderer[camera.id]) {
  27825. var textureType = 0;
  27826. if (this._engine.getCaps().textureHalfFloatRender) {
  27827. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27828. }
  27829. else if (this._engine.getCaps().textureFloatRender) {
  27830. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27831. }
  27832. else {
  27833. throw "Depth renderer does not support int texture type";
  27834. }
  27835. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27836. }
  27837. return this._depthRenderer[camera.id];
  27838. };
  27839. /**
  27840. * Disables a depth renderer for a given camera
  27841. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27842. */
  27843. Scene.prototype.disableDepthRenderer = function (camera) {
  27844. camera = camera || this.activeCamera;
  27845. if (!camera || !this._depthRenderer[camera.id]) {
  27846. return;
  27847. }
  27848. this._depthRenderer[camera.id].dispose();
  27849. delete this._depthRenderer[camera.id];
  27850. };
  27851. /**
  27852. * Enables a GeometryBufferRender and associates it with the scene
  27853. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27854. * @returns the GeometryBufferRenderer
  27855. */
  27856. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27857. if (ratio === void 0) { ratio = 1; }
  27858. if (this._geometryBufferRenderer) {
  27859. return this._geometryBufferRenderer;
  27860. }
  27861. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27862. if (!this._geometryBufferRenderer.isSupported) {
  27863. this._geometryBufferRenderer = null;
  27864. }
  27865. return this._geometryBufferRenderer;
  27866. };
  27867. /**
  27868. * Disables the GeometryBufferRender associated with the scene
  27869. */
  27870. Scene.prototype.disableGeometryBufferRenderer = function () {
  27871. if (!this._geometryBufferRenderer) {
  27872. return;
  27873. }
  27874. this._geometryBufferRenderer.dispose();
  27875. this._geometryBufferRenderer = null;
  27876. };
  27877. /**
  27878. * Freeze all materials
  27879. * A frozen material will not be updatable but should be faster to render
  27880. */
  27881. Scene.prototype.freezeMaterials = function () {
  27882. for (var i = 0; i < this.materials.length; i++) {
  27883. this.materials[i].freeze();
  27884. }
  27885. };
  27886. /**
  27887. * Unfreeze all materials
  27888. * A frozen material will not be updatable but should be faster to render
  27889. */
  27890. Scene.prototype.unfreezeMaterials = function () {
  27891. for (var i = 0; i < this.materials.length; i++) {
  27892. this.materials[i].unfreeze();
  27893. }
  27894. };
  27895. /**
  27896. * Releases all held ressources
  27897. */
  27898. Scene.prototype.dispose = function () {
  27899. this.beforeRender = null;
  27900. this.afterRender = null;
  27901. this.skeletons = [];
  27902. this.morphTargetManagers = [];
  27903. this.importedMeshesFiles = new Array();
  27904. this.stopAllAnimations();
  27905. this.resetCachedMaterial();
  27906. for (var key in this._depthRenderer) {
  27907. this._depthRenderer[key].dispose();
  27908. }
  27909. if (this._gamepadManager) {
  27910. this._gamepadManager.dispose();
  27911. this._gamepadManager = null;
  27912. }
  27913. // Smart arrays
  27914. if (this.activeCamera) {
  27915. this.activeCamera._activeMeshes.dispose();
  27916. this.activeCamera = null;
  27917. }
  27918. this._activeMeshes.dispose();
  27919. this._renderingManager.dispose();
  27920. this._processedMaterials.dispose();
  27921. this._activeParticleSystems.dispose();
  27922. this._activeSkeletons.dispose();
  27923. this._softwareSkinnedMeshes.dispose();
  27924. this._renderTargets.dispose();
  27925. this._registeredForLateAnimationBindings.dispose();
  27926. if (this._boundingBoxRenderer) {
  27927. this._boundingBoxRenderer.dispose();
  27928. }
  27929. this._meshesForIntersections.dispose();
  27930. this._toBeDisposed.dispose();
  27931. // Abort active requests
  27932. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27933. var request = _a[_i];
  27934. request.abort();
  27935. }
  27936. // Debug layer
  27937. if (this._debugLayer) {
  27938. this._debugLayer.hide();
  27939. }
  27940. // Events
  27941. this.onDisposeObservable.notifyObservers(this);
  27942. this.onDisposeObservable.clear();
  27943. this.onBeforeRenderObservable.clear();
  27944. this.onAfterRenderObservable.clear();
  27945. this.onBeforeRenderTargetsRenderObservable.clear();
  27946. this.onAfterRenderTargetsRenderObservable.clear();
  27947. this.onAfterStepObservable.clear();
  27948. this.onBeforeStepObservable.clear();
  27949. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27950. this.onAfterActiveMeshesEvaluationObservable.clear();
  27951. this.onBeforeParticlesRenderingObservable.clear();
  27952. this.onAfterParticlesRenderingObservable.clear();
  27953. this.onBeforeSpritesRenderingObservable.clear();
  27954. this.onAfterSpritesRenderingObservable.clear();
  27955. this.onBeforeDrawPhaseObservable.clear();
  27956. this.onAfterDrawPhaseObservable.clear();
  27957. this.onBeforePhysicsObservable.clear();
  27958. this.onAfterPhysicsObservable.clear();
  27959. this.onBeforeAnimationsObservable.clear();
  27960. this.onAfterAnimationsObservable.clear();
  27961. this.onDataLoadedObservable.clear();
  27962. this.detachControl();
  27963. // Release sounds & sounds tracks
  27964. if (BABYLON.AudioEngine) {
  27965. this.disposeSounds();
  27966. }
  27967. // VR Helper
  27968. if (this.VRHelper) {
  27969. this.VRHelper.dispose();
  27970. }
  27971. // Detach cameras
  27972. var canvas = this._engine.getRenderingCanvas();
  27973. if (canvas) {
  27974. var index;
  27975. for (index = 0; index < this.cameras.length; index++) {
  27976. this.cameras[index].detachControl(canvas);
  27977. }
  27978. }
  27979. // Release animation groups
  27980. while (this.animationGroups.length) {
  27981. this.animationGroups[0].dispose();
  27982. }
  27983. // Release lights
  27984. while (this.lights.length) {
  27985. this.lights[0].dispose();
  27986. }
  27987. // Release meshes
  27988. while (this.meshes.length) {
  27989. this.meshes[0].dispose(true);
  27990. }
  27991. while (this.transformNodes.length) {
  27992. this.removeTransformNode(this.transformNodes[0]);
  27993. }
  27994. // Release cameras
  27995. while (this.cameras.length) {
  27996. this.cameras[0].dispose();
  27997. }
  27998. // Release materials
  27999. if (this.defaultMaterial) {
  28000. this.defaultMaterial.dispose();
  28001. }
  28002. while (this.multiMaterials.length) {
  28003. this.multiMaterials[0].dispose();
  28004. }
  28005. while (this.materials.length) {
  28006. this.materials[0].dispose();
  28007. }
  28008. // Release particles
  28009. while (this.particleSystems.length) {
  28010. this.particleSystems[0].dispose();
  28011. }
  28012. // Release sprites
  28013. while (this.spriteManagers.length) {
  28014. this.spriteManagers[0].dispose();
  28015. }
  28016. // Release postProcesses
  28017. while (this.postProcesses.length) {
  28018. this.postProcesses[0].dispose();
  28019. }
  28020. // Release layers
  28021. while (this.layers.length) {
  28022. this.layers[0].dispose();
  28023. }
  28024. while (this.effectLayers.length) {
  28025. this.effectLayers[0].dispose();
  28026. }
  28027. // Release textures
  28028. while (this.textures.length) {
  28029. this.textures[0].dispose();
  28030. }
  28031. // Release UBO
  28032. this._sceneUbo.dispose();
  28033. if (this._alternateSceneUbo) {
  28034. this._alternateSceneUbo.dispose();
  28035. }
  28036. // Post-processes
  28037. this.postProcessManager.dispose();
  28038. if (this._postProcessRenderPipelineManager) {
  28039. this._postProcessRenderPipelineManager.dispose();
  28040. }
  28041. // Physics
  28042. if (this._physicsEngine) {
  28043. this.disablePhysicsEngine();
  28044. }
  28045. // Remove from engine
  28046. index = this._engine.scenes.indexOf(this);
  28047. if (index > -1) {
  28048. this._engine.scenes.splice(index, 1);
  28049. }
  28050. this._engine.wipeCaches(true);
  28051. this._isDisposed = true;
  28052. };
  28053. Object.defineProperty(Scene.prototype, "isDisposed", {
  28054. /**
  28055. * Gets if the scene is already disposed
  28056. */
  28057. get: function () {
  28058. return this._isDisposed;
  28059. },
  28060. enumerable: true,
  28061. configurable: true
  28062. });
  28063. /**
  28064. * Releases sounds & soundtracks
  28065. */
  28066. Scene.prototype.disposeSounds = function () {
  28067. if (!this._mainSoundTrack) {
  28068. return;
  28069. }
  28070. this.mainSoundTrack.dispose();
  28071. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28072. this.soundTracks[scIndex].dispose();
  28073. }
  28074. };
  28075. // Octrees
  28076. /**
  28077. * Get the world extend vectors with an optional filter
  28078. *
  28079. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28080. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28081. */
  28082. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28083. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28084. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28085. filterPredicate = filterPredicate || (function () { return true; });
  28086. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28087. mesh.computeWorldMatrix(true);
  28088. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28089. return;
  28090. }
  28091. var boundingInfo = mesh.getBoundingInfo();
  28092. var minBox = boundingInfo.boundingBox.minimumWorld;
  28093. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28094. BABYLON.Tools.CheckExtends(minBox, min, max);
  28095. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28096. });
  28097. return {
  28098. min: min,
  28099. max: max
  28100. };
  28101. };
  28102. /**
  28103. * Creates or updates the octree used to boost selection (picking)
  28104. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28105. * @param maxCapacity defines the maximum capacity per leaf
  28106. * @param maxDepth defines the maximum depth of the octree
  28107. * @returns an octree of AbstractMesh
  28108. */
  28109. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28110. if (maxCapacity === void 0) { maxCapacity = 64; }
  28111. if (maxDepth === void 0) { maxDepth = 2; }
  28112. if (!this._selectionOctree) {
  28113. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28114. }
  28115. var worldExtends = this.getWorldExtends();
  28116. // Update octree
  28117. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28118. return this._selectionOctree;
  28119. };
  28120. // Picking
  28121. /**
  28122. * Creates a ray that can be used to pick in the scene
  28123. * @param x defines the x coordinate of the origin (on-screen)
  28124. * @param y defines the y coordinate of the origin (on-screen)
  28125. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28126. * @param camera defines the camera to use for the picking
  28127. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28128. * @returns a Ray
  28129. */
  28130. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28131. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28132. var result = BABYLON.Ray.Zero();
  28133. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28134. return result;
  28135. };
  28136. /**
  28137. * Creates a ray that can be used to pick in the scene
  28138. * @param x defines the x coordinate of the origin (on-screen)
  28139. * @param y defines the y coordinate of the origin (on-screen)
  28140. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28141. * @param result defines the ray where to store the picking ray
  28142. * @param camera defines the camera to use for the picking
  28143. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28144. * @returns the current scene
  28145. */
  28146. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28147. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28148. var engine = this._engine;
  28149. if (!camera) {
  28150. if (!this.activeCamera)
  28151. throw new Error("Active camera not set");
  28152. camera = this.activeCamera;
  28153. }
  28154. var cameraViewport = camera.viewport;
  28155. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28156. // Moving coordinates to local viewport world
  28157. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28158. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28159. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28160. return this;
  28161. };
  28162. /**
  28163. * Creates a ray that can be used to pick in the scene
  28164. * @param x defines the x coordinate of the origin (on-screen)
  28165. * @param y defines the y coordinate of the origin (on-screen)
  28166. * @param camera defines the camera to use for the picking
  28167. * @returns a Ray
  28168. */
  28169. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28170. var result = BABYLON.Ray.Zero();
  28171. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28172. return result;
  28173. };
  28174. /**
  28175. * Creates a ray that can be used to pick in the scene
  28176. * @param x defines the x coordinate of the origin (on-screen)
  28177. * @param y defines the y coordinate of the origin (on-screen)
  28178. * @param result defines the ray where to store the picking ray
  28179. * @param camera defines the camera to use for the picking
  28180. * @returns the current scene
  28181. */
  28182. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28183. if (!BABYLON.PickingInfo) {
  28184. return this;
  28185. }
  28186. var engine = this._engine;
  28187. if (!camera) {
  28188. if (!this.activeCamera)
  28189. throw new Error("Active camera not set");
  28190. camera = this.activeCamera;
  28191. }
  28192. var cameraViewport = camera.viewport;
  28193. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28194. var identity = BABYLON.Matrix.Identity();
  28195. // Moving coordinates to local viewport world
  28196. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28197. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28198. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28199. return this;
  28200. };
  28201. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28202. if (!BABYLON.PickingInfo) {
  28203. return null;
  28204. }
  28205. var pickingInfo = null;
  28206. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28207. var mesh = this.meshes[meshIndex];
  28208. if (predicate) {
  28209. if (!predicate(mesh)) {
  28210. continue;
  28211. }
  28212. }
  28213. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28214. continue;
  28215. }
  28216. var world = mesh.getWorldMatrix();
  28217. var ray = rayFunction(world);
  28218. var result = mesh.intersects(ray, fastCheck);
  28219. if (!result || !result.hit)
  28220. continue;
  28221. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28222. continue;
  28223. pickingInfo = result;
  28224. if (fastCheck) {
  28225. break;
  28226. }
  28227. }
  28228. return pickingInfo || new BABYLON.PickingInfo();
  28229. };
  28230. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28231. if (!BABYLON.PickingInfo) {
  28232. return null;
  28233. }
  28234. var pickingInfos = new Array();
  28235. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28236. var mesh = this.meshes[meshIndex];
  28237. if (predicate) {
  28238. if (!predicate(mesh)) {
  28239. continue;
  28240. }
  28241. }
  28242. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28243. continue;
  28244. }
  28245. var world = mesh.getWorldMatrix();
  28246. var ray = rayFunction(world);
  28247. var result = mesh.intersects(ray, false);
  28248. if (!result || !result.hit)
  28249. continue;
  28250. pickingInfos.push(result);
  28251. }
  28252. return pickingInfos;
  28253. };
  28254. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28255. if (!BABYLON.PickingInfo) {
  28256. return null;
  28257. }
  28258. var pickingInfo = null;
  28259. if (!camera) {
  28260. if (!this.activeCamera) {
  28261. return null;
  28262. }
  28263. camera = this.activeCamera;
  28264. }
  28265. if (this.spriteManagers.length > 0) {
  28266. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28267. var spriteManager = this.spriteManagers[spriteIndex];
  28268. if (!spriteManager.isPickable) {
  28269. continue;
  28270. }
  28271. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28272. if (!result || !result.hit)
  28273. continue;
  28274. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28275. continue;
  28276. pickingInfo = result;
  28277. if (fastCheck) {
  28278. break;
  28279. }
  28280. }
  28281. }
  28282. return pickingInfo || new BABYLON.PickingInfo();
  28283. };
  28284. /** Launch a ray to try to pick a mesh in the scene
  28285. * @param x position on screen
  28286. * @param y position on screen
  28287. * @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
  28288. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28289. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28290. * @returns a PickingInfo
  28291. */
  28292. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28293. var _this = this;
  28294. if (!BABYLON.PickingInfo) {
  28295. return null;
  28296. }
  28297. return this._internalPick(function (world) {
  28298. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28299. return _this._tempPickingRay;
  28300. }, predicate, fastCheck);
  28301. };
  28302. /** Launch a ray to try to pick a sprite in the scene
  28303. * @param x position on screen
  28304. * @param y position on screen
  28305. * @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
  28306. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28307. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28308. * @returns a PickingInfo
  28309. */
  28310. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28311. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28312. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28313. };
  28314. /** Use the given ray to pick a mesh in the scene
  28315. * @param ray The ray to use to pick meshes
  28316. * @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
  28317. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28318. * @returns a PickingInfo
  28319. */
  28320. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28321. var _this = this;
  28322. return this._internalPick(function (world) {
  28323. if (!_this._pickWithRayInverseMatrix) {
  28324. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28325. }
  28326. world.invertToRef(_this._pickWithRayInverseMatrix);
  28327. if (!_this._cachedRayForTransform) {
  28328. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28329. }
  28330. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28331. return _this._cachedRayForTransform;
  28332. }, predicate, fastCheck);
  28333. };
  28334. /**
  28335. * Launch a ray to try to pick a mesh in the scene
  28336. * @param x X position on screen
  28337. * @param y Y position on screen
  28338. * @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
  28339. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28340. * @returns an array of PickingInfo
  28341. */
  28342. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28343. var _this = this;
  28344. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28345. };
  28346. /**
  28347. * Launch a ray to try to pick a mesh in the scene
  28348. * @param ray Ray to use
  28349. * @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
  28350. * @returns an array of PickingInfo
  28351. */
  28352. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28353. var _this = this;
  28354. return this._internalMultiPick(function (world) {
  28355. if (!_this._pickWithRayInverseMatrix) {
  28356. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28357. }
  28358. world.invertToRef(_this._pickWithRayInverseMatrix);
  28359. if (!_this._cachedRayForTransform) {
  28360. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28361. }
  28362. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28363. return _this._cachedRayForTransform;
  28364. }, predicate);
  28365. };
  28366. /**
  28367. * Force the value of meshUnderPointer
  28368. * @param mesh defines the mesh to use
  28369. */
  28370. Scene.prototype.setPointerOverMesh = function (mesh) {
  28371. if (this._pointerOverMesh === mesh) {
  28372. return;
  28373. }
  28374. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28375. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28376. }
  28377. this._pointerOverMesh = mesh;
  28378. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28379. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28380. }
  28381. };
  28382. /**
  28383. * Gets the mesh under the pointer
  28384. * @returns a Mesh or null if no mesh is under the pointer
  28385. */
  28386. Scene.prototype.getPointerOverMesh = function () {
  28387. return this._pointerOverMesh;
  28388. };
  28389. /**
  28390. * Force the sprite under the pointer
  28391. * @param sprite defines the sprite to use
  28392. */
  28393. Scene.prototype.setPointerOverSprite = function (sprite) {
  28394. if (this._pointerOverSprite === sprite) {
  28395. return;
  28396. }
  28397. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28398. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28399. }
  28400. this._pointerOverSprite = sprite;
  28401. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28402. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28403. }
  28404. };
  28405. /**
  28406. * Gets the sprite under the pointer
  28407. * @returns a Sprite or null if no sprite is under the pointer
  28408. */
  28409. Scene.prototype.getPointerOverSprite = function () {
  28410. return this._pointerOverSprite;
  28411. };
  28412. // Physics
  28413. /**
  28414. * Gets the current physics engine
  28415. * @returns a PhysicsEngine or null if none attached
  28416. */
  28417. Scene.prototype.getPhysicsEngine = function () {
  28418. return this._physicsEngine;
  28419. };
  28420. /**
  28421. * Enables physics to the current scene
  28422. * @param gravity defines the scene's gravity for the physics engine
  28423. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28424. * @return a boolean indicating if the physics engine was initialized
  28425. */
  28426. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28427. if (gravity === void 0) { gravity = null; }
  28428. if (this._physicsEngine) {
  28429. return true;
  28430. }
  28431. try {
  28432. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28433. return true;
  28434. }
  28435. catch (e) {
  28436. BABYLON.Tools.Error(e.message);
  28437. return false;
  28438. }
  28439. };
  28440. /**
  28441. * Disables and disposes the physics engine associated with the scene
  28442. */
  28443. Scene.prototype.disablePhysicsEngine = function () {
  28444. if (!this._physicsEngine) {
  28445. return;
  28446. }
  28447. this._physicsEngine.dispose();
  28448. this._physicsEngine = null;
  28449. };
  28450. /**
  28451. * Gets a boolean indicating if there is an active physics engine
  28452. * @returns a boolean indicating if there is an active physics engine
  28453. */
  28454. Scene.prototype.isPhysicsEnabled = function () {
  28455. return this._physicsEngine !== undefined;
  28456. };
  28457. /**
  28458. * Deletes a physics compound impostor
  28459. * @param compound defines the compound to delete
  28460. */
  28461. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28462. var mesh = compound.parts[0].mesh;
  28463. if (mesh.physicsImpostor) {
  28464. mesh.physicsImpostor.dispose( /*true*/);
  28465. mesh.physicsImpostor = null;
  28466. }
  28467. };
  28468. // Misc.
  28469. /** @hidden */
  28470. Scene.prototype._rebuildGeometries = function () {
  28471. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28472. var geometry = _a[_i];
  28473. geometry._rebuild();
  28474. }
  28475. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28476. var mesh = _c[_b];
  28477. mesh._rebuild();
  28478. }
  28479. if (this.postProcessManager) {
  28480. this.postProcessManager._rebuild();
  28481. }
  28482. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28483. var layer = _e[_d];
  28484. layer._rebuild();
  28485. }
  28486. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28487. var effectLayer = _g[_f];
  28488. effectLayer._rebuild();
  28489. }
  28490. if (this._boundingBoxRenderer) {
  28491. this._boundingBoxRenderer._rebuild();
  28492. }
  28493. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28494. var system = _j[_h];
  28495. system.rebuild();
  28496. }
  28497. if (this._postProcessRenderPipelineManager) {
  28498. this._postProcessRenderPipelineManager._rebuild();
  28499. }
  28500. };
  28501. /** @hidden */
  28502. Scene.prototype._rebuildTextures = function () {
  28503. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28504. var texture = _a[_i];
  28505. texture._rebuild();
  28506. }
  28507. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28508. };
  28509. /**
  28510. * Creates a default light for the scene.
  28511. * @param replace Whether to replace the existing lights in the scene.
  28512. */
  28513. Scene.prototype.createDefaultLight = function (replace) {
  28514. if (replace === void 0) { replace = false; }
  28515. // Dispose existing light in replace mode.
  28516. if (replace) {
  28517. if (this.lights) {
  28518. for (var i = 0; i < this.lights.length; i++) {
  28519. this.lights[i].dispose();
  28520. }
  28521. }
  28522. }
  28523. // Light
  28524. if (this.lights.length === 0) {
  28525. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28526. }
  28527. };
  28528. /**
  28529. * Creates a default camera for the scene.
  28530. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28531. * @param replace Whether to replace the existing active camera in the scene.
  28532. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28533. */
  28534. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28535. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28536. if (replace === void 0) { replace = false; }
  28537. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28538. // Dispose existing camera in replace mode.
  28539. if (replace) {
  28540. if (this.activeCamera) {
  28541. this.activeCamera.dispose();
  28542. this.activeCamera = null;
  28543. }
  28544. }
  28545. // Camera
  28546. if (!this.activeCamera) {
  28547. var worldExtends = this.getWorldExtends();
  28548. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28549. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28550. var camera;
  28551. var radius = worldSize.length() * 1.5;
  28552. // empty scene scenario!
  28553. if (!isFinite(radius)) {
  28554. radius = 1;
  28555. worldCenter.copyFromFloats(0, 0, 0);
  28556. }
  28557. if (createArcRotateCamera) {
  28558. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28559. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28560. arcRotateCamera.wheelPrecision = 100 / radius;
  28561. camera = arcRotateCamera;
  28562. }
  28563. else {
  28564. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28565. freeCamera.setTarget(worldCenter);
  28566. camera = freeCamera;
  28567. }
  28568. camera.minZ = radius * 0.01;
  28569. camera.maxZ = radius * 1000;
  28570. camera.speed = radius * 0.2;
  28571. this.activeCamera = camera;
  28572. var canvas = this.getEngine().getRenderingCanvas();
  28573. if (attachCameraControls && canvas) {
  28574. camera.attachControl(canvas);
  28575. }
  28576. }
  28577. };
  28578. /**
  28579. * Creates a default camera and a default light
  28580. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28581. * @param replace defines if the camera and/or light will replace the existing ones
  28582. * @param attachCameraControls defines if attachControl will be called on the new camera
  28583. */
  28584. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28585. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28586. if (replace === void 0) { replace = false; }
  28587. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28588. this.createDefaultLight(replace);
  28589. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28590. };
  28591. /**
  28592. * Creates a new sky box
  28593. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28594. * @param environmentTexture defines the texture to use as environment texture
  28595. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28596. * @param scale defines the overall scale of the skybox
  28597. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28598. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28599. * @returns a new mesh holding the sky box
  28600. */
  28601. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28602. if (pbr === void 0) { pbr = false; }
  28603. if (scale === void 0) { scale = 1000; }
  28604. if (blur === void 0) { blur = 0; }
  28605. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28606. if (!environmentTexture) {
  28607. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28608. return null;
  28609. }
  28610. if (setGlobalEnvTexture) {
  28611. if (environmentTexture) {
  28612. this.environmentTexture = environmentTexture;
  28613. }
  28614. }
  28615. // Skybox
  28616. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28617. if (pbr) {
  28618. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28619. hdrSkyboxMaterial.backFaceCulling = false;
  28620. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28621. if (hdrSkyboxMaterial.reflectionTexture) {
  28622. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28623. }
  28624. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28625. hdrSkyboxMaterial.disableLighting = true;
  28626. hdrSkyboxMaterial.twoSidedLighting = true;
  28627. hdrSkybox.infiniteDistance = true;
  28628. hdrSkybox.material = hdrSkyboxMaterial;
  28629. }
  28630. else {
  28631. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28632. skyboxMaterial.backFaceCulling = false;
  28633. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28634. if (skyboxMaterial.reflectionTexture) {
  28635. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28636. }
  28637. skyboxMaterial.disableLighting = true;
  28638. hdrSkybox.infiniteDistance = true;
  28639. hdrSkybox.material = skyboxMaterial;
  28640. }
  28641. return hdrSkybox;
  28642. };
  28643. /**
  28644. * Creates a new environment
  28645. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28646. * @param options defines the options you can use to configure the environment
  28647. * @returns the new EnvironmentHelper
  28648. */
  28649. Scene.prototype.createDefaultEnvironment = function (options) {
  28650. if (BABYLON.EnvironmentHelper) {
  28651. return new BABYLON.EnvironmentHelper(options, this);
  28652. }
  28653. return null;
  28654. };
  28655. /**
  28656. * Creates a new VREXperienceHelper
  28657. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28658. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28659. * @returns a new VREXperienceHelper
  28660. */
  28661. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28662. if (webVROptions === void 0) { webVROptions = {}; }
  28663. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28664. };
  28665. // Tags
  28666. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28667. if (tagsQuery === undefined) {
  28668. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28669. return list;
  28670. }
  28671. var listByTags = [];
  28672. forEach = forEach || (function (item) { return; });
  28673. for (var i in list) {
  28674. var item = list[i];
  28675. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28676. listByTags.push(item);
  28677. forEach(item);
  28678. }
  28679. }
  28680. return listByTags;
  28681. };
  28682. /**
  28683. * Get a list of meshes by tags
  28684. * @param tagsQuery defines the tags query to use
  28685. * @param forEach defines a predicate used to filter results
  28686. * @returns an array of Mesh
  28687. */
  28688. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28689. return this._getByTags(this.meshes, tagsQuery, forEach);
  28690. };
  28691. /**
  28692. * Get a list of cameras by tags
  28693. * @param tagsQuery defines the tags query to use
  28694. * @param forEach defines a predicate used to filter results
  28695. * @returns an array of Camera
  28696. */
  28697. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28698. return this._getByTags(this.cameras, tagsQuery, forEach);
  28699. };
  28700. /**
  28701. * Get a list of lights by tags
  28702. * @param tagsQuery defines the tags query to use
  28703. * @param forEach defines a predicate used to filter results
  28704. * @returns an array of Light
  28705. */
  28706. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28707. return this._getByTags(this.lights, tagsQuery, forEach);
  28708. };
  28709. /**
  28710. * Get a list of materials by tags
  28711. * @param tagsQuery defines the tags query to use
  28712. * @param forEach defines a predicate used to filter results
  28713. * @returns an array of Material
  28714. */
  28715. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28716. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28717. };
  28718. /**
  28719. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28720. * This allowed control for front to back rendering or reversly depending of the special needs.
  28721. *
  28722. * @param renderingGroupId The rendering group id corresponding to its index
  28723. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28724. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28725. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28726. */
  28727. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28728. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28729. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28730. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28731. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28732. };
  28733. /**
  28734. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28735. *
  28736. * @param renderingGroupId The rendering group id corresponding to its index
  28737. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28738. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28739. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28740. */
  28741. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28742. if (depth === void 0) { depth = true; }
  28743. if (stencil === void 0) { stencil = true; }
  28744. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28745. };
  28746. /**
  28747. * Will flag all materials as dirty to trigger new shader compilation
  28748. * @param flag defines the flag used to specify which material part must be marked as dirty
  28749. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28750. */
  28751. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28752. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28753. var material = _a[_i];
  28754. if (predicate && !predicate(material)) {
  28755. continue;
  28756. }
  28757. material.markAsDirty(flag);
  28758. }
  28759. };
  28760. /** @hidden */
  28761. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28762. var _this = this;
  28763. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28764. this._activeRequests.push(request);
  28765. request.onCompleteObservable.add(function (request) {
  28766. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28767. });
  28768. return request;
  28769. };
  28770. /** @hidden */
  28771. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28772. var _this = this;
  28773. return new Promise(function (resolve, reject) {
  28774. _this._loadFile(url, function (data) {
  28775. resolve(data);
  28776. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28777. reject(exception);
  28778. });
  28779. });
  28780. };
  28781. // Statics
  28782. Scene._FOGMODE_NONE = 0;
  28783. Scene._FOGMODE_EXP = 1;
  28784. Scene._FOGMODE_EXP2 = 2;
  28785. Scene._FOGMODE_LINEAR = 3;
  28786. Scene._uniqueIdCounter = 0;
  28787. /**
  28788. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28789. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28790. */
  28791. Scene.MinDeltaTime = 1.0;
  28792. /**
  28793. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28794. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28795. */
  28796. Scene.MaxDeltaTime = 1000.0;
  28797. /** The distance in pixel that you have to move to prevent some events */
  28798. Scene.DragMovementThreshold = 10; // in pixels
  28799. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28800. Scene.LongPressDelay = 500; // in milliseconds
  28801. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28802. Scene.DoubleClickDelay = 300; // in milliseconds
  28803. /** If you need to check double click without raising a single click at first click, enable this flag */
  28804. Scene.ExclusiveDoubleClickMode = false;
  28805. return Scene;
  28806. }());
  28807. BABYLON.Scene = Scene;
  28808. })(BABYLON || (BABYLON = {}));
  28809. //# sourceMappingURL=babylon.scene.js.map
  28810. var BABYLON;
  28811. (function (BABYLON) {
  28812. /**
  28813. * Set of assets to keep when moving a scene into an asset container.
  28814. */
  28815. var KeepAssets = /** @class */ (function () {
  28816. function KeepAssets() {
  28817. /**
  28818. * Cameras to keep.
  28819. */
  28820. this.cameras = new Array();
  28821. /**
  28822. * Lights to keep.
  28823. */
  28824. this.lights = new Array();
  28825. /**
  28826. * Meshes to keep.
  28827. */
  28828. this.meshes = new Array();
  28829. /**
  28830. * Skeletons to keep.
  28831. */
  28832. this.skeletons = new Array();
  28833. /**
  28834. * ParticleSystems to keep.
  28835. */
  28836. this.particleSystems = new Array();
  28837. /**
  28838. * Animations to keep.
  28839. */
  28840. this.animations = new Array();
  28841. /**
  28842. * AnimationGroups to keep.
  28843. */
  28844. this.animationGroups = new Array();
  28845. /**
  28846. * MultiMaterials to keep.
  28847. */
  28848. this.multiMaterials = new Array();
  28849. /**
  28850. * Materials to keep.
  28851. */
  28852. this.materials = new Array();
  28853. /**
  28854. * MorphTargetManagers to keep.
  28855. */
  28856. this.morphTargetManagers = new Array();
  28857. /**
  28858. * Geometries to keep.
  28859. */
  28860. this.geometries = new Array();
  28861. /**
  28862. * TransformNodes to keep.
  28863. */
  28864. this.transformNodes = new Array();
  28865. /**
  28866. * LensFlareSystems to keep.
  28867. */
  28868. this.lensFlareSystems = new Array();
  28869. /**
  28870. * ShadowGenerators to keep.
  28871. */
  28872. this.shadowGenerators = new Array();
  28873. /**
  28874. * ActionManagers to keep.
  28875. */
  28876. this.actionManagers = new Array();
  28877. /**
  28878. * Sounds to keep.
  28879. */
  28880. this.sounds = new Array();
  28881. /**
  28882. * Textures to keep.
  28883. */
  28884. this.textures = new Array();
  28885. /**
  28886. * Effect layers to keep.
  28887. */
  28888. this.effectLayers = new Array();
  28889. }
  28890. return KeepAssets;
  28891. }());
  28892. BABYLON.KeepAssets = KeepAssets;
  28893. /**
  28894. * Container with a set of assets that can be added or removed from a scene.
  28895. */
  28896. var AssetContainer = /** @class */ (function () {
  28897. /**
  28898. * Instantiates an AssetContainer.
  28899. * @param scene The scene the AssetContainer belongs to.
  28900. */
  28901. function AssetContainer(scene) {
  28902. // Objects
  28903. /**
  28904. * Cameras populated in the container.
  28905. */
  28906. this.cameras = new Array();
  28907. /**
  28908. * Lights populated in the container.
  28909. */
  28910. this.lights = new Array();
  28911. /**
  28912. * Meshes populated in the container.
  28913. */
  28914. this.meshes = new Array();
  28915. /**
  28916. * Skeletons populated in the container.
  28917. */
  28918. this.skeletons = new Array();
  28919. /**
  28920. * ParticleSystems populated in the container.
  28921. */
  28922. this.particleSystems = new Array();
  28923. /**
  28924. * Animations populated in the container.
  28925. */
  28926. this.animations = new Array();
  28927. /**
  28928. * AnimationGroups populated in the container.
  28929. */
  28930. this.animationGroups = new Array();
  28931. /**
  28932. * MultiMaterials populated in the container.
  28933. */
  28934. this.multiMaterials = new Array();
  28935. /**
  28936. * Materials populated in the container.
  28937. */
  28938. this.materials = new Array();
  28939. /**
  28940. * MorphTargetManagers populated in the container.
  28941. */
  28942. this.morphTargetManagers = new Array();
  28943. /**
  28944. * Geometries populated in the container.
  28945. */
  28946. this.geometries = new Array();
  28947. /**
  28948. * TransformNodes populated in the container.
  28949. */
  28950. this.transformNodes = new Array();
  28951. /**
  28952. * LensFlareSystems populated in the container.
  28953. */
  28954. this.lensFlareSystems = new Array();
  28955. /**
  28956. * ShadowGenerators populated in the container.
  28957. */
  28958. this.shadowGenerators = new Array();
  28959. /**
  28960. * ActionManagers populated in the container.
  28961. */
  28962. this.actionManagers = new Array();
  28963. /**
  28964. * Sounds populated in the container.
  28965. */
  28966. this.sounds = new Array();
  28967. /**
  28968. * Textures populated in the container.
  28969. */
  28970. this.textures = new Array();
  28971. /**
  28972. * Effect layers populated in the container.
  28973. */
  28974. this.effectLayers = new Array();
  28975. this.scene = scene;
  28976. }
  28977. /**
  28978. * Adds all the assets from the container to the scene.
  28979. */
  28980. AssetContainer.prototype.addAllToScene = function () {
  28981. var _this = this;
  28982. this.cameras.forEach(function (o) {
  28983. _this.scene.addCamera(o);
  28984. });
  28985. this.lights.forEach(function (o) {
  28986. _this.scene.addLight(o);
  28987. });
  28988. this.meshes.forEach(function (o) {
  28989. _this.scene.addMesh(o);
  28990. });
  28991. this.skeletons.forEach(function (o) {
  28992. _this.scene.addSkeleton(o);
  28993. });
  28994. this.particleSystems.forEach(function (o) {
  28995. _this.scene.addParticleSystem(o);
  28996. });
  28997. this.animations.forEach(function (o) {
  28998. _this.scene.addAnimation(o);
  28999. });
  29000. this.animationGroups.forEach(function (o) {
  29001. _this.scene.addAnimationGroup(o);
  29002. });
  29003. this.multiMaterials.forEach(function (o) {
  29004. _this.scene.addMultiMaterial(o);
  29005. });
  29006. this.materials.forEach(function (o) {
  29007. _this.scene.addMaterial(o);
  29008. });
  29009. this.morphTargetManagers.forEach(function (o) {
  29010. _this.scene.addMorphTargetManager(o);
  29011. });
  29012. this.geometries.forEach(function (o) {
  29013. _this.scene.addGeometry(o);
  29014. });
  29015. this.transformNodes.forEach(function (o) {
  29016. _this.scene.addTransformNode(o);
  29017. });
  29018. this.lensFlareSystems.forEach(function (o) {
  29019. _this.scene.addLensFlareSystem(o);
  29020. });
  29021. this.actionManagers.forEach(function (o) {
  29022. _this.scene.addActionManager(o);
  29023. });
  29024. this.sounds.forEach(function (o) {
  29025. o.play();
  29026. o.autoplay = true;
  29027. _this.scene.mainSoundTrack.AddSound(o);
  29028. });
  29029. this.textures.forEach(function (o) {
  29030. _this.scene.addTexture(o);
  29031. });
  29032. this.effectLayers.forEach(function (o) {
  29033. _this.scene.addEffectLayer(o);
  29034. });
  29035. };
  29036. /**
  29037. * Removes all the assets in the container from the scene
  29038. */
  29039. AssetContainer.prototype.removeAllFromScene = function () {
  29040. var _this = this;
  29041. this.cameras.forEach(function (o) {
  29042. _this.scene.removeCamera(o);
  29043. });
  29044. this.lights.forEach(function (o) {
  29045. _this.scene.removeLight(o);
  29046. });
  29047. this.meshes.forEach(function (o) {
  29048. _this.scene.removeMesh(o);
  29049. });
  29050. this.skeletons.forEach(function (o) {
  29051. _this.scene.removeSkeleton(o);
  29052. });
  29053. this.particleSystems.forEach(function (o) {
  29054. _this.scene.removeParticleSystem(o);
  29055. });
  29056. this.animations.forEach(function (o) {
  29057. _this.scene.removeAnimation(o);
  29058. });
  29059. this.animationGroups.forEach(function (o) {
  29060. _this.scene.removeAnimationGroup(o);
  29061. });
  29062. this.multiMaterials.forEach(function (o) {
  29063. _this.scene.removeMultiMaterial(o);
  29064. });
  29065. this.materials.forEach(function (o) {
  29066. _this.scene.removeMaterial(o);
  29067. });
  29068. this.morphTargetManagers.forEach(function (o) {
  29069. _this.scene.removeMorphTargetManager(o);
  29070. });
  29071. this.geometries.forEach(function (o) {
  29072. _this.scene.removeGeometry(o);
  29073. });
  29074. this.transformNodes.forEach(function (o) {
  29075. _this.scene.removeTransformNode(o);
  29076. });
  29077. this.lensFlareSystems.forEach(function (o) {
  29078. _this.scene.removeLensFlareSystem(o);
  29079. });
  29080. this.actionManagers.forEach(function (o) {
  29081. _this.scene.removeActionManager(o);
  29082. });
  29083. this.sounds.forEach(function (o) {
  29084. o.stop();
  29085. o.autoplay = false;
  29086. _this.scene.mainSoundTrack.RemoveSound(o);
  29087. });
  29088. this.textures.forEach(function (o) {
  29089. _this.scene.removeTexture(o);
  29090. });
  29091. this.effectLayers.forEach(function (o) {
  29092. _this.scene.removeEffectLayer(o);
  29093. });
  29094. };
  29095. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29096. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29097. var asset = sourceAssets_1[_i];
  29098. var move = true;
  29099. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29100. var keepAsset = keepAssets_1[_a];
  29101. if (asset === keepAsset) {
  29102. move = false;
  29103. break;
  29104. }
  29105. }
  29106. if (move) {
  29107. targetAssets.push(asset);
  29108. }
  29109. }
  29110. };
  29111. /**
  29112. * Removes all the assets contained in the scene and adds them to the container.
  29113. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29114. */
  29115. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29116. if (keepAssets === undefined) {
  29117. keepAssets = new KeepAssets();
  29118. }
  29119. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29120. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29121. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29122. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29123. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29124. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29125. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29126. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29127. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29128. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29129. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29130. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29131. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29132. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29133. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29134. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29135. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29136. this.removeAllFromScene();
  29137. };
  29138. return AssetContainer;
  29139. }());
  29140. BABYLON.AssetContainer = AssetContainer;
  29141. })(BABYLON || (BABYLON = {}));
  29142. //# sourceMappingURL=babylon.assetContainer.js.map
  29143. var BABYLON;
  29144. (function (BABYLON) {
  29145. var Buffer = /** @class */ (function () {
  29146. /**
  29147. * Constructor
  29148. * @param engine the engine
  29149. * @param data the data to use for this buffer
  29150. * @param updatable whether the data is updatable
  29151. * @param stride the stride (optional)
  29152. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29153. * @param instanced whether the buffer is instanced (optional)
  29154. * @param useBytes set to true if the stride in in bytes (optional)
  29155. */
  29156. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29157. if (stride === void 0) { stride = 0; }
  29158. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29159. if (instanced === void 0) { instanced = false; }
  29160. if (useBytes === void 0) { useBytes = false; }
  29161. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29162. this._engine = engine.getScene().getEngine();
  29163. }
  29164. else {
  29165. this._engine = engine;
  29166. }
  29167. this._updatable = updatable;
  29168. this._instanced = instanced;
  29169. this._data = data;
  29170. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29171. if (!postponeInternalCreation) { // by default
  29172. this.create();
  29173. }
  29174. }
  29175. /**
  29176. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29177. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29178. * @param offset defines offset in the buffer (0 by default)
  29179. * @param size defines the size in floats of attributes (position is 3 for instance)
  29180. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29181. * @param instanced defines if the vertex buffer contains indexed data
  29182. * @param useBytes defines if the offset and stride are in bytes
  29183. * @returns the new vertex buffer
  29184. */
  29185. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29186. if (useBytes === void 0) { useBytes = false; }
  29187. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29188. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29189. // a lot of these parameters are ignored as they are overriden by the buffer
  29190. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29191. };
  29192. // Properties
  29193. Buffer.prototype.isUpdatable = function () {
  29194. return this._updatable;
  29195. };
  29196. Buffer.prototype.getData = function () {
  29197. return this._data;
  29198. };
  29199. Buffer.prototype.getBuffer = function () {
  29200. return this._buffer;
  29201. };
  29202. /**
  29203. * Gets the stride in float32 units (i.e. byte stride / 4).
  29204. * May not be an integer if the byte stride is not divisible by 4.
  29205. * DEPRECATED. Use byteStride instead.
  29206. * @returns the stride in float32 units
  29207. */
  29208. Buffer.prototype.getStrideSize = function () {
  29209. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29210. };
  29211. // Methods
  29212. Buffer.prototype.create = function (data) {
  29213. if (data === void 0) { data = null; }
  29214. if (!data && this._buffer) {
  29215. return; // nothing to do
  29216. }
  29217. data = data || this._data;
  29218. if (!data) {
  29219. return;
  29220. }
  29221. if (!this._buffer) { // create buffer
  29222. if (this._updatable) {
  29223. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29224. this._data = data;
  29225. }
  29226. else {
  29227. this._buffer = this._engine.createVertexBuffer(data);
  29228. }
  29229. }
  29230. else if (this._updatable) { // update buffer
  29231. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29232. this._data = data;
  29233. }
  29234. };
  29235. Buffer.prototype._rebuild = function () {
  29236. this._buffer = null;
  29237. this.create(this._data);
  29238. };
  29239. Buffer.prototype.update = function (data) {
  29240. this.create(data);
  29241. };
  29242. /**
  29243. * Updates the data directly.
  29244. * @param data the new data
  29245. * @param offset the new offset
  29246. * @param vertexCount the vertex count (optional)
  29247. * @param useBytes set to true if the offset is in bytes
  29248. */
  29249. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29250. if (useBytes === void 0) { useBytes = false; }
  29251. if (!this._buffer) {
  29252. return;
  29253. }
  29254. if (this._updatable) { // update buffer
  29255. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29256. this._data = null;
  29257. }
  29258. };
  29259. Buffer.prototype.dispose = function () {
  29260. if (!this._buffer) {
  29261. return;
  29262. }
  29263. if (this._engine._releaseBuffer(this._buffer)) {
  29264. this._buffer = null;
  29265. }
  29266. };
  29267. return Buffer;
  29268. }());
  29269. BABYLON.Buffer = Buffer;
  29270. })(BABYLON || (BABYLON = {}));
  29271. //# sourceMappingURL=babylon.buffer.js.map
  29272. var BABYLON;
  29273. (function (BABYLON) {
  29274. var VertexBuffer = /** @class */ (function () {
  29275. /**
  29276. * Constructor
  29277. * @param engine the engine
  29278. * @param data the data to use for this vertex buffer
  29279. * @param kind the vertex buffer kind
  29280. * @param updatable whether the data is updatable
  29281. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29282. * @param stride the stride (optional)
  29283. * @param instanced whether the buffer is instanced (optional)
  29284. * @param offset the offset of the data (optional)
  29285. * @param size the number of components (optional)
  29286. * @param type the type of the component (optional)
  29287. * @param normalized whether the data contains normalized data (optional)
  29288. * @param useBytes set to true if stride and offset are in bytes (optional)
  29289. */
  29290. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29291. if (normalized === void 0) { normalized = false; }
  29292. if (useBytes === void 0) { useBytes = false; }
  29293. if (data instanceof BABYLON.Buffer) {
  29294. this._buffer = data;
  29295. this._ownsBuffer = false;
  29296. }
  29297. else {
  29298. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29299. this._ownsBuffer = true;
  29300. }
  29301. this._kind = kind;
  29302. if (type == undefined) {
  29303. var data_1 = this.getData();
  29304. this.type = VertexBuffer.FLOAT;
  29305. if (data_1 instanceof Int8Array)
  29306. this.type = VertexBuffer.BYTE;
  29307. else if (data_1 instanceof Uint8Array)
  29308. this.type = VertexBuffer.UNSIGNED_BYTE;
  29309. else if (data_1 instanceof Int16Array)
  29310. this.type = VertexBuffer.SHORT;
  29311. else if (data_1 instanceof Uint16Array)
  29312. this.type = VertexBuffer.UNSIGNED_SHORT;
  29313. else if (data_1 instanceof Int32Array)
  29314. this.type = VertexBuffer.INT;
  29315. else if (data_1 instanceof Uint32Array)
  29316. this.type = VertexBuffer.UNSIGNED_INT;
  29317. }
  29318. else {
  29319. this.type = type;
  29320. }
  29321. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29322. if (useBytes) {
  29323. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29324. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29325. this.byteOffset = offset || 0;
  29326. }
  29327. else {
  29328. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29329. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29330. this.byteOffset = (offset || 0) * typeByteLength;
  29331. }
  29332. this.normalized = normalized;
  29333. this._instanced = instanced !== undefined ? instanced : false;
  29334. this._instanceDivisor = instanced ? 1 : 0;
  29335. }
  29336. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29337. /**
  29338. * Gets or sets the instance divisor when in instanced mode
  29339. */
  29340. get: function () {
  29341. return this._instanceDivisor;
  29342. },
  29343. set: function (value) {
  29344. this._instanceDivisor = value;
  29345. if (value == 0) {
  29346. this._instanced = false;
  29347. }
  29348. else {
  29349. this._instanced = true;
  29350. }
  29351. },
  29352. enumerable: true,
  29353. configurable: true
  29354. });
  29355. VertexBuffer.prototype._rebuild = function () {
  29356. if (!this._buffer) {
  29357. return;
  29358. }
  29359. this._buffer._rebuild();
  29360. };
  29361. /**
  29362. * Returns the kind of the VertexBuffer (string).
  29363. */
  29364. VertexBuffer.prototype.getKind = function () {
  29365. return this._kind;
  29366. };
  29367. // Properties
  29368. /**
  29369. * Boolean : is the VertexBuffer updatable ?
  29370. */
  29371. VertexBuffer.prototype.isUpdatable = function () {
  29372. return this._buffer.isUpdatable();
  29373. };
  29374. /**
  29375. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29376. */
  29377. VertexBuffer.prototype.getData = function () {
  29378. return this._buffer.getData();
  29379. };
  29380. /**
  29381. * Returns the WebGLBuffer associated to the VertexBuffer.
  29382. */
  29383. VertexBuffer.prototype.getBuffer = function () {
  29384. return this._buffer.getBuffer();
  29385. };
  29386. /**
  29387. * Returns the stride as a multiple of the type byte length.
  29388. * DEPRECATED. Use byteStride instead.
  29389. */
  29390. VertexBuffer.prototype.getStrideSize = function () {
  29391. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29392. };
  29393. /**
  29394. * Returns the offset as a multiple of the type byte length.
  29395. * DEPRECATED. Use byteOffset instead.
  29396. */
  29397. VertexBuffer.prototype.getOffset = function () {
  29398. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29399. };
  29400. /**
  29401. * Returns the number of components per vertex attribute (integer).
  29402. */
  29403. VertexBuffer.prototype.getSize = function () {
  29404. return this._size;
  29405. };
  29406. /**
  29407. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29408. */
  29409. VertexBuffer.prototype.getIsInstanced = function () {
  29410. return this._instanced;
  29411. };
  29412. /**
  29413. * Returns the instancing divisor, zero for non-instanced (integer).
  29414. */
  29415. VertexBuffer.prototype.getInstanceDivisor = function () {
  29416. return this._instanceDivisor;
  29417. };
  29418. // Methods
  29419. /**
  29420. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29421. * Returns the created WebGLBuffer.
  29422. */
  29423. VertexBuffer.prototype.create = function (data) {
  29424. return this._buffer.create(data);
  29425. };
  29426. /**
  29427. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29428. * This function will create a new buffer if the current one is not updatable
  29429. * Returns the updated WebGLBuffer.
  29430. */
  29431. VertexBuffer.prototype.update = function (data) {
  29432. return this._buffer.update(data);
  29433. };
  29434. /**
  29435. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29436. * Returns the directly updated WebGLBuffer.
  29437. * @param data the new data
  29438. * @param offset the new offset
  29439. * @param useBytes set to true if the offset is in bytes
  29440. */
  29441. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29442. if (useBytes === void 0) { useBytes = false; }
  29443. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29444. };
  29445. /**
  29446. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29447. */
  29448. VertexBuffer.prototype.dispose = function () {
  29449. if (this._ownsBuffer) {
  29450. this._buffer.dispose();
  29451. }
  29452. };
  29453. /**
  29454. * Enumerates each value of this vertex buffer as numbers.
  29455. * @param count the number of values to enumerate
  29456. * @param callback the callback function called for each value
  29457. */
  29458. VertexBuffer.prototype.forEach = function (count, callback) {
  29459. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29460. };
  29461. Object.defineProperty(VertexBuffer, "PositionKind", {
  29462. get: function () {
  29463. return VertexBuffer._PositionKind;
  29464. },
  29465. enumerable: true,
  29466. configurable: true
  29467. });
  29468. Object.defineProperty(VertexBuffer, "NormalKind", {
  29469. get: function () {
  29470. return VertexBuffer._NormalKind;
  29471. },
  29472. enumerable: true,
  29473. configurable: true
  29474. });
  29475. Object.defineProperty(VertexBuffer, "TangentKind", {
  29476. get: function () {
  29477. return VertexBuffer._TangentKind;
  29478. },
  29479. enumerable: true,
  29480. configurable: true
  29481. });
  29482. Object.defineProperty(VertexBuffer, "UVKind", {
  29483. get: function () {
  29484. return VertexBuffer._UVKind;
  29485. },
  29486. enumerable: true,
  29487. configurable: true
  29488. });
  29489. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29490. get: function () {
  29491. return VertexBuffer._UV2Kind;
  29492. },
  29493. enumerable: true,
  29494. configurable: true
  29495. });
  29496. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29497. get: function () {
  29498. return VertexBuffer._UV3Kind;
  29499. },
  29500. enumerable: true,
  29501. configurable: true
  29502. });
  29503. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29504. get: function () {
  29505. return VertexBuffer._UV4Kind;
  29506. },
  29507. enumerable: true,
  29508. configurable: true
  29509. });
  29510. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29511. get: function () {
  29512. return VertexBuffer._UV5Kind;
  29513. },
  29514. enumerable: true,
  29515. configurable: true
  29516. });
  29517. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29518. get: function () {
  29519. return VertexBuffer._UV6Kind;
  29520. },
  29521. enumerable: true,
  29522. configurable: true
  29523. });
  29524. Object.defineProperty(VertexBuffer, "ColorKind", {
  29525. get: function () {
  29526. return VertexBuffer._ColorKind;
  29527. },
  29528. enumerable: true,
  29529. configurable: true
  29530. });
  29531. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29532. get: function () {
  29533. return VertexBuffer._MatricesIndicesKind;
  29534. },
  29535. enumerable: true,
  29536. configurable: true
  29537. });
  29538. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29539. get: function () {
  29540. return VertexBuffer._MatricesWeightsKind;
  29541. },
  29542. enumerable: true,
  29543. configurable: true
  29544. });
  29545. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29546. get: function () {
  29547. return VertexBuffer._MatricesIndicesExtraKind;
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29553. get: function () {
  29554. return VertexBuffer._MatricesWeightsExtraKind;
  29555. },
  29556. enumerable: true,
  29557. configurable: true
  29558. });
  29559. /**
  29560. * Deduces the stride given a kind.
  29561. * @param kind The kind string to deduce
  29562. * @returns The deduced stride
  29563. */
  29564. VertexBuffer.DeduceStride = function (kind) {
  29565. switch (kind) {
  29566. case VertexBuffer.UVKind:
  29567. case VertexBuffer.UV2Kind:
  29568. case VertexBuffer.UV3Kind:
  29569. case VertexBuffer.UV4Kind:
  29570. case VertexBuffer.UV5Kind:
  29571. case VertexBuffer.UV6Kind:
  29572. return 2;
  29573. case VertexBuffer.NormalKind:
  29574. case VertexBuffer.PositionKind:
  29575. return 3;
  29576. case VertexBuffer.ColorKind:
  29577. case VertexBuffer.MatricesIndicesKind:
  29578. case VertexBuffer.MatricesIndicesExtraKind:
  29579. case VertexBuffer.MatricesWeightsKind:
  29580. case VertexBuffer.MatricesWeightsExtraKind:
  29581. case VertexBuffer.TangentKind:
  29582. return 4;
  29583. default:
  29584. throw new Error("Invalid kind '" + kind + "'");
  29585. }
  29586. };
  29587. /**
  29588. * Gets the byte length of the given type.
  29589. * @param type the type
  29590. * @returns the number of bytes
  29591. */
  29592. VertexBuffer.GetTypeByteLength = function (type) {
  29593. switch (type) {
  29594. case VertexBuffer.BYTE:
  29595. case VertexBuffer.UNSIGNED_BYTE:
  29596. return 1;
  29597. case VertexBuffer.SHORT:
  29598. case VertexBuffer.UNSIGNED_SHORT:
  29599. return 2;
  29600. case VertexBuffer.INT:
  29601. case VertexBuffer.FLOAT:
  29602. return 4;
  29603. default:
  29604. throw new Error("Invalid type '" + type + "'");
  29605. }
  29606. };
  29607. /**
  29608. * Enumerates each value of the given parameters as numbers.
  29609. * @param data the data to enumerate
  29610. * @param byteOffset the byte offset of the data
  29611. * @param byteStride the byte stride of the data
  29612. * @param componentCount the number of components per element
  29613. * @param componentType the type of the component
  29614. * @param count the total number of components
  29615. * @param normalized whether the data is normalized
  29616. * @param callback the callback function called for each value
  29617. */
  29618. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29619. if (data instanceof Array) {
  29620. var offset = byteOffset / 4;
  29621. var stride = byteStride / 4;
  29622. for (var index = 0; index < count; index += componentCount) {
  29623. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29624. callback(data[offset + componentIndex], index + componentIndex);
  29625. }
  29626. offset += stride;
  29627. }
  29628. }
  29629. else {
  29630. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29631. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29632. for (var index = 0; index < count; index += componentCount) {
  29633. var componentByteOffset = byteOffset;
  29634. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29635. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29636. callback(value, index + componentIndex);
  29637. componentByteOffset += componentByteLength;
  29638. }
  29639. byteOffset += byteStride;
  29640. }
  29641. }
  29642. };
  29643. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29644. switch (type) {
  29645. case VertexBuffer.BYTE: {
  29646. var value = dataView.getInt8(byteOffset);
  29647. if (normalized) {
  29648. value = Math.max(value / 127, -1);
  29649. }
  29650. return value;
  29651. }
  29652. case VertexBuffer.UNSIGNED_BYTE: {
  29653. var value = dataView.getUint8(byteOffset);
  29654. if (normalized) {
  29655. value = value / 255;
  29656. }
  29657. return value;
  29658. }
  29659. case VertexBuffer.SHORT: {
  29660. var value = dataView.getInt16(byteOffset, true);
  29661. if (normalized) {
  29662. value = Math.max(value / 16383, -1);
  29663. }
  29664. return value;
  29665. }
  29666. case VertexBuffer.UNSIGNED_SHORT: {
  29667. var value = dataView.getUint16(byteOffset, true);
  29668. if (normalized) {
  29669. value = value / 65535;
  29670. }
  29671. return value;
  29672. }
  29673. case VertexBuffer.FLOAT: {
  29674. return dataView.getFloat32(byteOffset, true);
  29675. }
  29676. default: {
  29677. throw new Error("Invalid component type " + type);
  29678. }
  29679. }
  29680. };
  29681. /**
  29682. * The byte type.
  29683. */
  29684. VertexBuffer.BYTE = 5120;
  29685. /**
  29686. * The unsigned byte type.
  29687. */
  29688. VertexBuffer.UNSIGNED_BYTE = 5121;
  29689. /**
  29690. * The short type.
  29691. */
  29692. VertexBuffer.SHORT = 5122;
  29693. /**
  29694. * The unsigned short type.
  29695. */
  29696. VertexBuffer.UNSIGNED_SHORT = 5123;
  29697. /**
  29698. * The integer type.
  29699. */
  29700. VertexBuffer.INT = 5124;
  29701. /**
  29702. * The unsigned integer type.
  29703. */
  29704. VertexBuffer.UNSIGNED_INT = 5125;
  29705. /**
  29706. * The float type.
  29707. */
  29708. VertexBuffer.FLOAT = 5126;
  29709. // Enums
  29710. VertexBuffer._PositionKind = "position";
  29711. VertexBuffer._NormalKind = "normal";
  29712. VertexBuffer._TangentKind = "tangent";
  29713. VertexBuffer._UVKind = "uv";
  29714. VertexBuffer._UV2Kind = "uv2";
  29715. VertexBuffer._UV3Kind = "uv3";
  29716. VertexBuffer._UV4Kind = "uv4";
  29717. VertexBuffer._UV5Kind = "uv5";
  29718. VertexBuffer._UV6Kind = "uv6";
  29719. VertexBuffer._ColorKind = "color";
  29720. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29721. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29722. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29723. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29724. return VertexBuffer;
  29725. }());
  29726. BABYLON.VertexBuffer = VertexBuffer;
  29727. })(BABYLON || (BABYLON = {}));
  29728. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29729. var BABYLON;
  29730. (function (BABYLON) {
  29731. /**
  29732. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29733. */
  29734. var DummyInternalTextureTracker = /** @class */ (function () {
  29735. function DummyInternalTextureTracker() {
  29736. /**
  29737. * Gets or set the previous tracker in the list
  29738. */
  29739. this.previous = null;
  29740. /**
  29741. * Gets or set the next tracker in the list
  29742. */
  29743. this.next = null;
  29744. }
  29745. return DummyInternalTextureTracker;
  29746. }());
  29747. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29748. })(BABYLON || (BABYLON = {}));
  29749. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29750. var BABYLON;
  29751. (function (BABYLON) {
  29752. /**
  29753. * Class used to store data associated with WebGL texture data for the engine
  29754. * This class should not be used directly
  29755. */
  29756. var InternalTexture = /** @class */ (function () {
  29757. /**
  29758. * Creates a new InternalTexture
  29759. * @param engine defines the engine to use
  29760. * @param dataSource defines the type of data that will be used
  29761. */
  29762. function InternalTexture(engine, dataSource) {
  29763. /**
  29764. * Observable called when the texture is loaded
  29765. */
  29766. this.onLoadedObservable = new BABYLON.Observable();
  29767. /**
  29768. * Gets or set the previous tracker in the list
  29769. */
  29770. this.previous = null;
  29771. /**
  29772. * Gets or set the next tracker in the list
  29773. */
  29774. this.next = null;
  29775. // Private
  29776. /** @hidden */
  29777. this._initialSlot = -1;
  29778. /** @hidden */
  29779. this._designatedSlot = -1;
  29780. /** @hidden */
  29781. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29782. /** @hidden */
  29783. this._comparisonFunction = 0;
  29784. /** @hidden */
  29785. this._references = 1;
  29786. this._engine = engine;
  29787. this._dataSource = dataSource;
  29788. this._webGLTexture = engine._createTexture();
  29789. }
  29790. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29791. /**
  29792. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29793. */
  29794. get: function () {
  29795. return this._dataSource;
  29796. },
  29797. enumerable: true,
  29798. configurable: true
  29799. });
  29800. /**
  29801. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29802. */
  29803. InternalTexture.prototype.incrementReferences = function () {
  29804. this._references++;
  29805. };
  29806. /**
  29807. * Change the size of the texture (not the size of the content)
  29808. * @param width defines the new width
  29809. * @param height defines the new height
  29810. * @param depth defines the new depth (1 by default)
  29811. */
  29812. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29813. if (depth === void 0) { depth = 1; }
  29814. this.width = width;
  29815. this.height = height;
  29816. this.depth = depth;
  29817. this.baseWidth = width;
  29818. this.baseHeight = height;
  29819. this.baseDepth = depth;
  29820. this._size = width * height * depth;
  29821. };
  29822. /** @hidden */
  29823. InternalTexture.prototype._rebuild = function () {
  29824. var _this = this;
  29825. var proxy;
  29826. this.isReady = false;
  29827. this._cachedCoordinatesMode = null;
  29828. this._cachedWrapU = null;
  29829. this._cachedWrapV = null;
  29830. this._cachedAnisotropicFilteringLevel = null;
  29831. switch (this._dataSource) {
  29832. case InternalTexture.DATASOURCE_TEMP:
  29833. return;
  29834. case InternalTexture.DATASOURCE_URL:
  29835. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29836. _this.isReady = true;
  29837. }, null, this._buffer, undefined, this.format);
  29838. proxy._swapAndDie(this);
  29839. return;
  29840. case InternalTexture.DATASOURCE_RAW:
  29841. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29842. proxy._swapAndDie(this);
  29843. this.isReady = true;
  29844. return;
  29845. case InternalTexture.DATASOURCE_RAW3D:
  29846. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29847. proxy._swapAndDie(this);
  29848. this.isReady = true;
  29849. return;
  29850. case InternalTexture.DATASOURCE_DYNAMIC:
  29851. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29852. proxy._swapAndDie(this);
  29853. // The engine will make sure to update content so no need to flag it as isReady = true
  29854. return;
  29855. case InternalTexture.DATASOURCE_RENDERTARGET:
  29856. var options = new BABYLON.RenderTargetCreationOptions();
  29857. options.generateDepthBuffer = this._generateDepthBuffer;
  29858. options.generateMipMaps = this.generateMipMaps;
  29859. options.generateStencilBuffer = this._generateStencilBuffer;
  29860. options.samplingMode = this.samplingMode;
  29861. options.type = this.type;
  29862. if (this.isCube) {
  29863. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29864. }
  29865. else {
  29866. var size = {
  29867. width: this.width,
  29868. height: this.height
  29869. };
  29870. proxy = this._engine.createRenderTargetTexture(size, options);
  29871. }
  29872. proxy._swapAndDie(this);
  29873. this.isReady = true;
  29874. return;
  29875. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29876. var depthTextureOptions = {
  29877. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29878. comparisonFunction: this._comparisonFunction,
  29879. generateStencil: this._generateStencilBuffer,
  29880. isCube: this.isCube
  29881. };
  29882. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29883. proxy._swapAndDie(this);
  29884. this.isReady = true;
  29885. return;
  29886. case InternalTexture.DATASOURCE_CUBE:
  29887. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29888. _this.isReady = true;
  29889. }, null, this.format, this._extension);
  29890. proxy._swapAndDie(this);
  29891. return;
  29892. case InternalTexture.DATASOURCE_CUBERAW:
  29893. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29894. proxy._swapAndDie(this);
  29895. this.isReady = true;
  29896. return;
  29897. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29898. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29899. if (proxy) {
  29900. proxy._swapAndDie(_this);
  29901. }
  29902. _this.isReady = true;
  29903. }, null, this.format, this._extension);
  29904. return;
  29905. }
  29906. };
  29907. InternalTexture.prototype._swapAndDie = function (target) {
  29908. target._webGLTexture = this._webGLTexture;
  29909. if (this._framebuffer) {
  29910. target._framebuffer = this._framebuffer;
  29911. }
  29912. if (this._depthStencilBuffer) {
  29913. target._depthStencilBuffer = this._depthStencilBuffer;
  29914. }
  29915. if (this._lodTextureHigh) {
  29916. if (target._lodTextureHigh) {
  29917. target._lodTextureHigh.dispose();
  29918. }
  29919. target._lodTextureHigh = this._lodTextureHigh;
  29920. }
  29921. if (this._lodTextureMid) {
  29922. if (target._lodTextureMid) {
  29923. target._lodTextureMid.dispose();
  29924. }
  29925. target._lodTextureMid = this._lodTextureMid;
  29926. }
  29927. if (this._lodTextureLow) {
  29928. if (target._lodTextureLow) {
  29929. target._lodTextureLow.dispose();
  29930. }
  29931. target._lodTextureLow = this._lodTextureLow;
  29932. }
  29933. var cache = this._engine.getLoadedTexturesCache();
  29934. var index = cache.indexOf(this);
  29935. if (index !== -1) {
  29936. cache.splice(index, 1);
  29937. }
  29938. };
  29939. /**
  29940. * Dispose the current allocated resources
  29941. */
  29942. InternalTexture.prototype.dispose = function () {
  29943. if (!this._webGLTexture) {
  29944. return;
  29945. }
  29946. this._references--;
  29947. if (this._references === 0) {
  29948. this._engine._releaseTexture(this);
  29949. this._webGLTexture = null;
  29950. this.previous = null;
  29951. this.next = null;
  29952. }
  29953. };
  29954. /**
  29955. * The source of the texture data is unknown
  29956. */
  29957. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29958. /**
  29959. * Texture data comes from an URL
  29960. */
  29961. InternalTexture.DATASOURCE_URL = 1;
  29962. /**
  29963. * Texture data is only used for temporary storage
  29964. */
  29965. InternalTexture.DATASOURCE_TEMP = 2;
  29966. /**
  29967. * Texture data comes from raw data (ArrayBuffer)
  29968. */
  29969. InternalTexture.DATASOURCE_RAW = 3;
  29970. /**
  29971. * Texture content is dynamic (video or dynamic texture)
  29972. */
  29973. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29974. /**
  29975. * Texture content is generated by rendering to it
  29976. */
  29977. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29978. /**
  29979. * Texture content is part of a multi render target process
  29980. */
  29981. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29982. /**
  29983. * Texture data comes from a cube data file
  29984. */
  29985. InternalTexture.DATASOURCE_CUBE = 7;
  29986. /**
  29987. * Texture data comes from a raw cube data
  29988. */
  29989. InternalTexture.DATASOURCE_CUBERAW = 8;
  29990. /**
  29991. * Texture data come from a prefiltered cube data file
  29992. */
  29993. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29994. /**
  29995. * Texture content is raw 3D data
  29996. */
  29997. InternalTexture.DATASOURCE_RAW3D = 10;
  29998. /**
  29999. * Texture content is a depth texture
  30000. */
  30001. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30002. return InternalTexture;
  30003. }());
  30004. BABYLON.InternalTexture = InternalTexture;
  30005. })(BABYLON || (BABYLON = {}));
  30006. //# sourceMappingURL=babylon.internalTexture.js.map
  30007. var BABYLON;
  30008. (function (BABYLON) {
  30009. var BaseTexture = /** @class */ (function () {
  30010. function BaseTexture(scene) {
  30011. this._hasAlpha = false;
  30012. this.getAlphaFromRGB = false;
  30013. this.level = 1;
  30014. this.coordinatesIndex = 0;
  30015. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30016. /**
  30017. * | Value | Type | Description |
  30018. * | ----- | ------------------ | ----------- |
  30019. * | 0 | CLAMP_ADDRESSMODE | |
  30020. * | 1 | WRAP_ADDRESSMODE | |
  30021. * | 2 | MIRROR_ADDRESSMODE | |
  30022. */
  30023. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30024. /**
  30025. * | Value | Type | Description |
  30026. * | ----- | ------------------ | ----------- |
  30027. * | 0 | CLAMP_ADDRESSMODE | |
  30028. * | 1 | WRAP_ADDRESSMODE | |
  30029. * | 2 | MIRROR_ADDRESSMODE | |
  30030. */
  30031. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30032. /**
  30033. * | Value | Type | Description |
  30034. * | ----- | ------------------ | ----------- |
  30035. * | 0 | CLAMP_ADDRESSMODE | |
  30036. * | 1 | WRAP_ADDRESSMODE | |
  30037. * | 2 | MIRROR_ADDRESSMODE | |
  30038. */
  30039. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30040. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30041. this.isCube = false;
  30042. this.is3D = false;
  30043. this.gammaSpace = true;
  30044. this.invertZ = false;
  30045. this.lodLevelInAlpha = false;
  30046. this.lodGenerationOffset = 0.0;
  30047. this.lodGenerationScale = 0.8;
  30048. this.isRenderTarget = false;
  30049. this.animations = new Array();
  30050. /**
  30051. * An event triggered when the texture is disposed.
  30052. */
  30053. this.onDisposeObservable = new BABYLON.Observable();
  30054. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30055. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30056. if (this._scene) {
  30057. this._scene.textures.push(this);
  30058. }
  30059. this._uid = null;
  30060. }
  30061. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30062. get: function () {
  30063. return this._hasAlpha;
  30064. },
  30065. set: function (value) {
  30066. if (this._hasAlpha === value) {
  30067. return;
  30068. }
  30069. this._hasAlpha = value;
  30070. if (this._scene) {
  30071. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30072. }
  30073. },
  30074. enumerable: true,
  30075. configurable: true
  30076. });
  30077. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30078. get: function () {
  30079. return this._coordinatesMode;
  30080. },
  30081. /**
  30082. * How a texture is mapped.
  30083. *
  30084. * | Value | Type | Description |
  30085. * | ----- | ----------------------------------- | ----------- |
  30086. * | 0 | EXPLICIT_MODE | |
  30087. * | 1 | SPHERICAL_MODE | |
  30088. * | 2 | PLANAR_MODE | |
  30089. * | 3 | CUBIC_MODE | |
  30090. * | 4 | PROJECTION_MODE | |
  30091. * | 5 | SKYBOX_MODE | |
  30092. * | 6 | INVCUBIC_MODE | |
  30093. * | 7 | EQUIRECTANGULAR_MODE | |
  30094. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30095. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30096. */
  30097. set: function (value) {
  30098. if (this._coordinatesMode === value) {
  30099. return;
  30100. }
  30101. this._coordinatesMode = value;
  30102. if (this._scene) {
  30103. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30104. }
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(BaseTexture.prototype, "uid", {
  30110. get: function () {
  30111. if (!this._uid) {
  30112. this._uid = BABYLON.Tools.RandomId();
  30113. }
  30114. return this._uid;
  30115. },
  30116. enumerable: true,
  30117. configurable: true
  30118. });
  30119. BaseTexture.prototype.toString = function () {
  30120. return this.name;
  30121. };
  30122. BaseTexture.prototype.getClassName = function () {
  30123. return "BaseTexture";
  30124. };
  30125. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30126. set: function (callback) {
  30127. if (this._onDisposeObserver) {
  30128. this.onDisposeObservable.remove(this._onDisposeObserver);
  30129. }
  30130. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30131. },
  30132. enumerable: true,
  30133. configurable: true
  30134. });
  30135. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30136. get: function () {
  30137. return true;
  30138. },
  30139. enumerable: true,
  30140. configurable: true
  30141. });
  30142. BaseTexture.prototype.getScene = function () {
  30143. return this._scene;
  30144. };
  30145. BaseTexture.prototype.getTextureMatrix = function () {
  30146. return BABYLON.Matrix.IdentityReadOnly;
  30147. };
  30148. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30149. return BABYLON.Matrix.IdentityReadOnly;
  30150. };
  30151. BaseTexture.prototype.getInternalTexture = function () {
  30152. return this._texture;
  30153. };
  30154. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30155. return !this.isBlocking || this.isReady();
  30156. };
  30157. BaseTexture.prototype.isReady = function () {
  30158. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30159. this.delayLoad();
  30160. return false;
  30161. }
  30162. if (this._texture) {
  30163. return this._texture.isReady;
  30164. }
  30165. return false;
  30166. };
  30167. BaseTexture.prototype.getSize = function () {
  30168. if (this._texture && this._texture.width) {
  30169. return new BABYLON.Size(this._texture.width, this._texture.height);
  30170. }
  30171. if (this._texture && this._texture._size) {
  30172. return new BABYLON.Size(this._texture._size, this._texture._size);
  30173. }
  30174. return BABYLON.Size.Zero();
  30175. };
  30176. BaseTexture.prototype.getBaseSize = function () {
  30177. if (!this.isReady() || !this._texture)
  30178. return BABYLON.Size.Zero();
  30179. if (this._texture._size) {
  30180. return new BABYLON.Size(this._texture._size, this._texture._size);
  30181. }
  30182. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30183. };
  30184. BaseTexture.prototype.scale = function (ratio) {
  30185. };
  30186. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30187. get: function () {
  30188. return false;
  30189. },
  30190. enumerable: true,
  30191. configurable: true
  30192. });
  30193. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30194. if (!this._scene) {
  30195. return null;
  30196. }
  30197. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30198. for (var index = 0; index < texturesCache.length; index++) {
  30199. var texturesCacheEntry = texturesCache[index];
  30200. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30201. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30202. texturesCacheEntry.incrementReferences();
  30203. return texturesCacheEntry;
  30204. }
  30205. }
  30206. }
  30207. return null;
  30208. };
  30209. BaseTexture.prototype._rebuild = function () {
  30210. };
  30211. BaseTexture.prototype.delayLoad = function () {
  30212. };
  30213. BaseTexture.prototype.clone = function () {
  30214. return null;
  30215. };
  30216. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30217. get: function () {
  30218. if (!this._texture) {
  30219. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30220. }
  30221. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30222. },
  30223. enumerable: true,
  30224. configurable: true
  30225. });
  30226. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30227. get: function () {
  30228. if (!this._texture) {
  30229. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30230. }
  30231. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. BaseTexture.prototype.readPixels = function (faceIndex) {
  30237. if (faceIndex === void 0) { faceIndex = 0; }
  30238. if (!this._texture) {
  30239. return null;
  30240. }
  30241. var size = this.getSize();
  30242. var scene = this.getScene();
  30243. if (!scene) {
  30244. return null;
  30245. }
  30246. var engine = scene.getEngine();
  30247. if (this._texture.isCube) {
  30248. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30249. }
  30250. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30251. };
  30252. BaseTexture.prototype.releaseInternalTexture = function () {
  30253. if (this._texture) {
  30254. this._texture.dispose();
  30255. this._texture = null;
  30256. }
  30257. };
  30258. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30259. get: function () {
  30260. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30261. return null;
  30262. }
  30263. if (!this._texture._sphericalPolynomial) {
  30264. this._texture._sphericalPolynomial =
  30265. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30266. }
  30267. return this._texture._sphericalPolynomial;
  30268. },
  30269. set: function (value) {
  30270. if (this._texture) {
  30271. this._texture._sphericalPolynomial = value;
  30272. }
  30273. },
  30274. enumerable: true,
  30275. configurable: true
  30276. });
  30277. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30278. get: function () {
  30279. if (this._texture) {
  30280. return this._texture._lodTextureHigh;
  30281. }
  30282. return null;
  30283. },
  30284. enumerable: true,
  30285. configurable: true
  30286. });
  30287. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30288. get: function () {
  30289. if (this._texture) {
  30290. return this._texture._lodTextureMid;
  30291. }
  30292. return null;
  30293. },
  30294. enumerable: true,
  30295. configurable: true
  30296. });
  30297. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30298. get: function () {
  30299. if (this._texture) {
  30300. return this._texture._lodTextureLow;
  30301. }
  30302. return null;
  30303. },
  30304. enumerable: true,
  30305. configurable: true
  30306. });
  30307. BaseTexture.prototype.dispose = function () {
  30308. if (!this._scene) {
  30309. return;
  30310. }
  30311. // Animations
  30312. this._scene.stopAnimation(this);
  30313. // Remove from scene
  30314. this._scene._removePendingData(this);
  30315. var index = this._scene.textures.indexOf(this);
  30316. if (index >= 0) {
  30317. this._scene.textures.splice(index, 1);
  30318. }
  30319. if (this._texture === undefined) {
  30320. return;
  30321. }
  30322. // Release
  30323. this.releaseInternalTexture();
  30324. // Callback
  30325. this.onDisposeObservable.notifyObservers(this);
  30326. this.onDisposeObservable.clear();
  30327. };
  30328. BaseTexture.prototype.serialize = function () {
  30329. if (!this.name) {
  30330. return null;
  30331. }
  30332. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30333. // Animations
  30334. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30335. return serializationObject;
  30336. };
  30337. BaseTexture.WhenAllReady = function (textures, callback) {
  30338. var numRemaining = textures.length;
  30339. if (numRemaining === 0) {
  30340. callback();
  30341. return;
  30342. }
  30343. var _loop_1 = function () {
  30344. texture = textures[i];
  30345. if (texture.isReady()) {
  30346. if (--numRemaining === 0) {
  30347. callback();
  30348. }
  30349. }
  30350. else {
  30351. onLoadObservable = texture.onLoadObservable;
  30352. var onLoadCallback_1 = function () {
  30353. onLoadObservable.removeCallback(onLoadCallback_1);
  30354. if (--numRemaining === 0) {
  30355. callback();
  30356. }
  30357. };
  30358. onLoadObservable.add(onLoadCallback_1);
  30359. }
  30360. };
  30361. var texture, onLoadObservable;
  30362. for (var i = 0; i < textures.length; i++) {
  30363. _loop_1();
  30364. }
  30365. };
  30366. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30367. __decorate([
  30368. BABYLON.serialize()
  30369. ], BaseTexture.prototype, "name", void 0);
  30370. __decorate([
  30371. BABYLON.serialize("hasAlpha")
  30372. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30373. __decorate([
  30374. BABYLON.serialize()
  30375. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30376. __decorate([
  30377. BABYLON.serialize()
  30378. ], BaseTexture.prototype, "level", void 0);
  30379. __decorate([
  30380. BABYLON.serialize()
  30381. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30382. __decorate([
  30383. BABYLON.serialize("coordinatesMode")
  30384. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30385. __decorate([
  30386. BABYLON.serialize()
  30387. ], BaseTexture.prototype, "wrapU", void 0);
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], BaseTexture.prototype, "wrapV", void 0);
  30391. __decorate([
  30392. BABYLON.serialize()
  30393. ], BaseTexture.prototype, "wrapR", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], BaseTexture.prototype, "isCube", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "is3D", void 0);
  30403. __decorate([
  30404. BABYLON.serialize()
  30405. ], BaseTexture.prototype, "gammaSpace", void 0);
  30406. __decorate([
  30407. BABYLON.serialize()
  30408. ], BaseTexture.prototype, "invertZ", void 0);
  30409. __decorate([
  30410. BABYLON.serialize()
  30411. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30418. __decorate([
  30419. BABYLON.serialize()
  30420. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30421. return BaseTexture;
  30422. }());
  30423. BABYLON.BaseTexture = BaseTexture;
  30424. })(BABYLON || (BABYLON = {}));
  30425. //# sourceMappingURL=babylon.baseTexture.js.map
  30426. var BABYLON;
  30427. (function (BABYLON) {
  30428. var Texture = /** @class */ (function (_super) {
  30429. __extends(Texture, _super);
  30430. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30431. if (noMipmap === void 0) { noMipmap = false; }
  30432. if (invertY === void 0) { invertY = true; }
  30433. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30434. if (onLoad === void 0) { onLoad = null; }
  30435. if (onError === void 0) { onError = null; }
  30436. if (buffer === void 0) { buffer = null; }
  30437. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30438. var _this = _super.call(this, scene) || this;
  30439. _this.uOffset = 0;
  30440. _this.vOffset = 0;
  30441. _this.uScale = 1.0;
  30442. _this.vScale = 1.0;
  30443. _this.uAng = 0;
  30444. _this.vAng = 0;
  30445. _this.wAng = 0;
  30446. _this._isBlocking = true;
  30447. _this.name = url || "";
  30448. _this.url = url;
  30449. _this._noMipmap = noMipmap;
  30450. _this._invertY = invertY;
  30451. _this._samplingMode = samplingMode;
  30452. _this._buffer = buffer;
  30453. _this._deleteBuffer = deleteBuffer;
  30454. if (format) {
  30455. _this._format = format;
  30456. }
  30457. scene = _this.getScene();
  30458. if (!scene) {
  30459. return _this;
  30460. }
  30461. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30462. var load = function () {
  30463. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30464. _this.onLoadObservable.notifyObservers(_this);
  30465. }
  30466. if (onLoad) {
  30467. onLoad();
  30468. }
  30469. if (!_this.isBlocking && scene) {
  30470. scene.resetCachedMaterial();
  30471. }
  30472. };
  30473. if (!_this.url) {
  30474. _this._delayedOnLoad = load;
  30475. _this._delayedOnError = onError;
  30476. return _this;
  30477. }
  30478. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30479. if (!_this._texture) {
  30480. if (!scene.useDelayedTextureLoading) {
  30481. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30482. if (deleteBuffer) {
  30483. delete _this._buffer;
  30484. }
  30485. }
  30486. else {
  30487. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30488. _this._delayedOnLoad = load;
  30489. _this._delayedOnError = onError;
  30490. }
  30491. }
  30492. else {
  30493. if (_this._texture.isReady) {
  30494. BABYLON.Tools.SetImmediate(function () { return load(); });
  30495. }
  30496. else {
  30497. _this._texture.onLoadedObservable.add(load);
  30498. }
  30499. }
  30500. return _this;
  30501. }
  30502. Object.defineProperty(Texture.prototype, "noMipmap", {
  30503. get: function () {
  30504. return this._noMipmap;
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(Texture.prototype, "isBlocking", {
  30510. get: function () {
  30511. return this._isBlocking;
  30512. },
  30513. set: function (value) {
  30514. this._isBlocking = value;
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. Object.defineProperty(Texture.prototype, "samplingMode", {
  30520. get: function () {
  30521. return this._samplingMode;
  30522. },
  30523. enumerable: true,
  30524. configurable: true
  30525. });
  30526. Texture.prototype.updateURL = function (url) {
  30527. this.url = url;
  30528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30529. this.delayLoad();
  30530. };
  30531. Texture.prototype.delayLoad = function () {
  30532. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30533. return;
  30534. }
  30535. var scene = this.getScene();
  30536. if (!scene) {
  30537. return;
  30538. }
  30539. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30540. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30541. if (!this._texture) {
  30542. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30543. if (this._deleteBuffer) {
  30544. delete this._buffer;
  30545. }
  30546. }
  30547. else {
  30548. if (this._delayedOnLoad) {
  30549. if (this._texture.isReady) {
  30550. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30551. }
  30552. else {
  30553. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30554. }
  30555. }
  30556. }
  30557. this._delayedOnLoad = null;
  30558. this._delayedOnError = null;
  30559. };
  30560. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30561. if (!this._texture) {
  30562. return;
  30563. }
  30564. var scene = this.getScene();
  30565. if (!scene) {
  30566. return;
  30567. }
  30568. this._samplingMode = samplingMode;
  30569. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30570. };
  30571. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30572. x *= this.uScale;
  30573. y *= this.vScale;
  30574. x -= 0.5 * this.uScale;
  30575. y -= 0.5 * this.vScale;
  30576. z -= 0.5;
  30577. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30578. t.x += 0.5 * this.uScale + this.uOffset;
  30579. t.y += 0.5 * this.vScale + this.vOffset;
  30580. t.z += 0.5;
  30581. };
  30582. Texture.prototype.getTextureMatrix = function () {
  30583. var _this = this;
  30584. if (this.uOffset === this._cachedUOffset &&
  30585. this.vOffset === this._cachedVOffset &&
  30586. this.uScale === this._cachedUScale &&
  30587. this.vScale === this._cachedVScale &&
  30588. this.uAng === this._cachedUAng &&
  30589. this.vAng === this._cachedVAng &&
  30590. this.wAng === this._cachedWAng) {
  30591. return this._cachedTextureMatrix;
  30592. }
  30593. this._cachedUOffset = this.uOffset;
  30594. this._cachedVOffset = this.vOffset;
  30595. this._cachedUScale = this.uScale;
  30596. this._cachedVScale = this.vScale;
  30597. this._cachedUAng = this.uAng;
  30598. this._cachedVAng = this.vAng;
  30599. this._cachedWAng = this.wAng;
  30600. if (!this._cachedTextureMatrix) {
  30601. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30602. this._rowGenerationMatrix = new BABYLON.Matrix();
  30603. this._t0 = BABYLON.Vector3.Zero();
  30604. this._t1 = BABYLON.Vector3.Zero();
  30605. this._t2 = BABYLON.Vector3.Zero();
  30606. }
  30607. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30608. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30609. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30610. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30611. this._t1.subtractInPlace(this._t0);
  30612. this._t2.subtractInPlace(this._t0);
  30613. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30614. this._cachedTextureMatrix.m[0] = this._t1.x;
  30615. this._cachedTextureMatrix.m[1] = this._t1.y;
  30616. this._cachedTextureMatrix.m[2] = this._t1.z;
  30617. this._cachedTextureMatrix.m[4] = this._t2.x;
  30618. this._cachedTextureMatrix.m[5] = this._t2.y;
  30619. this._cachedTextureMatrix.m[6] = this._t2.z;
  30620. this._cachedTextureMatrix.m[8] = this._t0.x;
  30621. this._cachedTextureMatrix.m[9] = this._t0.y;
  30622. this._cachedTextureMatrix.m[10] = this._t0.z;
  30623. var scene = this.getScene();
  30624. if (!scene) {
  30625. return this._cachedTextureMatrix;
  30626. }
  30627. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30628. return mat.hasTexture(_this);
  30629. });
  30630. return this._cachedTextureMatrix;
  30631. };
  30632. Texture.prototype.getReflectionTextureMatrix = function () {
  30633. var _this = this;
  30634. var scene = this.getScene();
  30635. if (!scene) {
  30636. return this._cachedTextureMatrix;
  30637. }
  30638. if (this.uOffset === this._cachedUOffset &&
  30639. this.vOffset === this._cachedVOffset &&
  30640. this.uScale === this._cachedUScale &&
  30641. this.vScale === this._cachedVScale &&
  30642. this.coordinatesMode === this._cachedCoordinatesMode) {
  30643. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30644. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30645. return this._cachedTextureMatrix;
  30646. }
  30647. }
  30648. else {
  30649. return this._cachedTextureMatrix;
  30650. }
  30651. }
  30652. if (!this._cachedTextureMatrix) {
  30653. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30654. }
  30655. if (!this._projectionModeMatrix) {
  30656. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30657. }
  30658. this._cachedUOffset = this.uOffset;
  30659. this._cachedVOffset = this.vOffset;
  30660. this._cachedUScale = this.uScale;
  30661. this._cachedVScale = this.vScale;
  30662. this._cachedCoordinatesMode = this.coordinatesMode;
  30663. switch (this.coordinatesMode) {
  30664. case Texture.PLANAR_MODE:
  30665. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30666. this._cachedTextureMatrix[0] = this.uScale;
  30667. this._cachedTextureMatrix[5] = this.vScale;
  30668. this._cachedTextureMatrix[12] = this.uOffset;
  30669. this._cachedTextureMatrix[13] = this.vOffset;
  30670. break;
  30671. case Texture.PROJECTION_MODE:
  30672. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30673. this._projectionModeMatrix.m[0] = 0.5;
  30674. this._projectionModeMatrix.m[5] = -0.5;
  30675. this._projectionModeMatrix.m[10] = 0.0;
  30676. this._projectionModeMatrix.m[12] = 0.5;
  30677. this._projectionModeMatrix.m[13] = 0.5;
  30678. this._projectionModeMatrix.m[14] = 1.0;
  30679. this._projectionModeMatrix.m[15] = 1.0;
  30680. var projectionMatrix = scene.getProjectionMatrix();
  30681. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30682. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30683. break;
  30684. default:
  30685. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30686. break;
  30687. }
  30688. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30689. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30690. });
  30691. return this._cachedTextureMatrix;
  30692. };
  30693. Texture.prototype.clone = function () {
  30694. var _this = this;
  30695. return BABYLON.SerializationHelper.Clone(function () {
  30696. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30697. }, this);
  30698. };
  30699. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30700. get: function () {
  30701. if (!this._onLoadObservable) {
  30702. this._onLoadObservable = new BABYLON.Observable();
  30703. }
  30704. return this._onLoadObservable;
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Texture.prototype.serialize = function () {
  30710. var serializationObject = _super.prototype.serialize.call(this);
  30711. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30712. serializationObject.base64String = this._buffer;
  30713. serializationObject.name = serializationObject.name.replace("data:", "");
  30714. }
  30715. serializationObject.invertY = this._invertY;
  30716. serializationObject.samplingMode = this.samplingMode;
  30717. return serializationObject;
  30718. };
  30719. Texture.prototype.getClassName = function () {
  30720. return "Texture";
  30721. };
  30722. Texture.prototype.dispose = function () {
  30723. _super.prototype.dispose.call(this);
  30724. if (this.onLoadObservable) {
  30725. this.onLoadObservable.clear();
  30726. this._onLoadObservable = null;
  30727. }
  30728. this._delayedOnLoad = null;
  30729. this._delayedOnError = null;
  30730. };
  30731. // Statics
  30732. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30733. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30734. if (onLoad === void 0) { onLoad = null; }
  30735. if (onError === void 0) { onError = null; }
  30736. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30737. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30738. };
  30739. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30740. if (parsedTexture.customType) {
  30741. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30742. // Update Sampling Mode
  30743. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30744. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30745. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30746. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30747. }
  30748. }
  30749. return parsedCustomTexture;
  30750. }
  30751. if (parsedTexture.isCube) {
  30752. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30753. }
  30754. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30755. return null;
  30756. }
  30757. var texture = BABYLON.SerializationHelper.Parse(function () {
  30758. var generateMipMaps = true;
  30759. if (parsedTexture.noMipmap) {
  30760. generateMipMaps = false;
  30761. }
  30762. if (parsedTexture.mirrorPlane) {
  30763. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30764. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30765. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30766. return mirrorTexture;
  30767. }
  30768. else if (parsedTexture.isRenderTarget) {
  30769. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30770. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30771. return renderTargetTexture;
  30772. }
  30773. else {
  30774. var texture;
  30775. if (parsedTexture.base64String) {
  30776. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30777. }
  30778. else {
  30779. var url = rootUrl + parsedTexture.name;
  30780. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30781. url = parsedTexture.url;
  30782. }
  30783. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30784. }
  30785. return texture;
  30786. }
  30787. }, parsedTexture, scene);
  30788. // Update Sampling Mode
  30789. if (parsedTexture.samplingMode) {
  30790. var sampling = parsedTexture.samplingMode;
  30791. if (texture._samplingMode !== sampling) {
  30792. texture.updateSamplingMode(sampling);
  30793. }
  30794. }
  30795. // Animations
  30796. if (parsedTexture.animations) {
  30797. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30798. var parsedAnimation = parsedTexture.animations[animationIndex];
  30799. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30800. }
  30801. }
  30802. return texture;
  30803. };
  30804. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30805. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30806. if (noMipmap === void 0) { noMipmap = false; }
  30807. if (invertY === void 0) { invertY = true; }
  30808. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30809. if (onLoad === void 0) { onLoad = null; }
  30810. if (onError === void 0) { onError = null; }
  30811. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30812. if (name.substr(0, 5) !== "data:") {
  30813. name = "data:" + name;
  30814. }
  30815. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30816. };
  30817. // Constants
  30818. Texture.NEAREST_SAMPLINGMODE = 1;
  30819. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30820. Texture.BILINEAR_SAMPLINGMODE = 2;
  30821. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30822. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30823. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30824. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30825. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30826. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30827. Texture.NEAREST_LINEAR = 7;
  30828. Texture.NEAREST_NEAREST = 8;
  30829. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30830. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30831. Texture.LINEAR_LINEAR = 11;
  30832. Texture.LINEAR_NEAREST = 12;
  30833. Texture.EXPLICIT_MODE = 0;
  30834. Texture.SPHERICAL_MODE = 1;
  30835. Texture.PLANAR_MODE = 2;
  30836. Texture.CUBIC_MODE = 3;
  30837. Texture.PROJECTION_MODE = 4;
  30838. Texture.SKYBOX_MODE = 5;
  30839. Texture.INVCUBIC_MODE = 6;
  30840. Texture.EQUIRECTANGULAR_MODE = 7;
  30841. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30842. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30843. Texture.CLAMP_ADDRESSMODE = 0;
  30844. Texture.WRAP_ADDRESSMODE = 1;
  30845. Texture.MIRROR_ADDRESSMODE = 2;
  30846. /**
  30847. * 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
  30848. */
  30849. Texture.UseSerializedUrlIfAny = false;
  30850. __decorate([
  30851. BABYLON.serialize()
  30852. ], Texture.prototype, "url", void 0);
  30853. __decorate([
  30854. BABYLON.serialize()
  30855. ], Texture.prototype, "uOffset", void 0);
  30856. __decorate([
  30857. BABYLON.serialize()
  30858. ], Texture.prototype, "vOffset", void 0);
  30859. __decorate([
  30860. BABYLON.serialize()
  30861. ], Texture.prototype, "uScale", void 0);
  30862. __decorate([
  30863. BABYLON.serialize()
  30864. ], Texture.prototype, "vScale", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], Texture.prototype, "uAng", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], Texture.prototype, "vAng", void 0);
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], Texture.prototype, "wAng", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], Texture.prototype, "isBlocking", null);
  30877. return Texture;
  30878. }(BABYLON.BaseTexture));
  30879. BABYLON.Texture = Texture;
  30880. })(BABYLON || (BABYLON = {}));
  30881. //# sourceMappingURL=babylon.texture.js.map
  30882. var BABYLON;
  30883. (function (BABYLON) {
  30884. /**
  30885. * @hidden
  30886. **/
  30887. var _InstancesBatch = /** @class */ (function () {
  30888. function _InstancesBatch() {
  30889. this.mustReturn = false;
  30890. this.visibleInstances = new Array();
  30891. this.renderSelf = new Array();
  30892. }
  30893. return _InstancesBatch;
  30894. }());
  30895. BABYLON._InstancesBatch = _InstancesBatch;
  30896. var Mesh = /** @class */ (function (_super) {
  30897. __extends(Mesh, _super);
  30898. /**
  30899. * @constructor
  30900. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30901. * @param {Scene} scene The scene to add this mesh to.
  30902. * @param {Node} parent The parent of this mesh, if it has one
  30903. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30904. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30905. * When false, achieved by calling a clone(), also passing False.
  30906. * This will make creation of children, recursive.
  30907. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30908. */
  30909. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30910. if (scene === void 0) { scene = null; }
  30911. if (parent === void 0) { parent = null; }
  30912. if (source === void 0) { source = null; }
  30913. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30914. var _this = _super.call(this, name, scene) || this;
  30915. // Events
  30916. /**
  30917. * An event triggered before rendering the mesh
  30918. */
  30919. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30920. /**
  30921. * An event triggered after rendering the mesh
  30922. */
  30923. _this.onAfterRenderObservable = new BABYLON.Observable();
  30924. /**
  30925. * An event triggered before drawing the mesh
  30926. */
  30927. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30928. // Members
  30929. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30930. _this.instances = new Array();
  30931. _this._LODLevels = new Array();
  30932. _this._visibleInstances = {};
  30933. _this._renderIdForInstances = new Array();
  30934. _this._batchCache = new _InstancesBatch();
  30935. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30936. // Use by builder only to know what orientation were the mesh build in.
  30937. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30938. _this.overrideMaterialSideOrientation = null;
  30939. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30940. // Will be used to save a source mesh reference, If any
  30941. _this._source = null;
  30942. scene = _this.getScene();
  30943. if (source) {
  30944. // Source mesh
  30945. _this._source = source;
  30946. // Geometry
  30947. if (source._geometry) {
  30948. source._geometry.applyToMesh(_this);
  30949. }
  30950. // Deep copy
  30951. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30952. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30953. // Metadata
  30954. if (source.metadata && source.metadata.clone) {
  30955. _this.metadata = source.metadata.clone();
  30956. }
  30957. else {
  30958. _this.metadata = source.metadata;
  30959. }
  30960. // Tags
  30961. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30962. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30963. }
  30964. // Parent
  30965. _this.parent = source.parent;
  30966. // Pivot
  30967. _this.setPivotMatrix(source.getPivotMatrix());
  30968. _this.id = name + "." + source.id;
  30969. // Material
  30970. _this.material = source.material;
  30971. var index;
  30972. if (!doNotCloneChildren) {
  30973. // Children
  30974. var directDescendants = source.getDescendants(true);
  30975. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30976. var child = directDescendants[index_1];
  30977. if (child.clone) {
  30978. child.clone(name + "." + child.name, _this);
  30979. }
  30980. }
  30981. }
  30982. // Physics clone
  30983. var physicsEngine = _this.getScene().getPhysicsEngine();
  30984. if (clonePhysicsImpostor && physicsEngine) {
  30985. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30986. if (impostor) {
  30987. _this.physicsImpostor = impostor.clone(_this);
  30988. }
  30989. }
  30990. // Particles
  30991. for (index = 0; index < scene.particleSystems.length; index++) {
  30992. var system = scene.particleSystems[index];
  30993. if (system.emitter === source) {
  30994. system.clone(system.name, _this);
  30995. }
  30996. }
  30997. _this.computeWorldMatrix(true);
  30998. }
  30999. // Parent
  31000. if (parent !== null) {
  31001. _this.parent = parent;
  31002. }
  31003. return _this;
  31004. }
  31005. Object.defineProperty(Mesh, "FRONTSIDE", {
  31006. /**
  31007. * Mesh side orientation : usually the external or front surface
  31008. */
  31009. get: function () {
  31010. return Mesh._FRONTSIDE;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. Object.defineProperty(Mesh, "BACKSIDE", {
  31016. /**
  31017. * Mesh side orientation : usually the internal or back surface
  31018. */
  31019. get: function () {
  31020. return Mesh._BACKSIDE;
  31021. },
  31022. enumerable: true,
  31023. configurable: true
  31024. });
  31025. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31026. /**
  31027. * Mesh side orientation : both internal and external or front and back surfaces
  31028. */
  31029. get: function () {
  31030. return Mesh._DOUBLESIDE;
  31031. },
  31032. enumerable: true,
  31033. configurable: true
  31034. });
  31035. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31036. /**
  31037. * Mesh side orientation : by default, `FRONTSIDE`
  31038. */
  31039. get: function () {
  31040. return Mesh._DEFAULTSIDE;
  31041. },
  31042. enumerable: true,
  31043. configurable: true
  31044. });
  31045. Object.defineProperty(Mesh, "NO_CAP", {
  31046. /**
  31047. * Mesh cap setting : no cap
  31048. */
  31049. get: function () {
  31050. return Mesh._NO_CAP;
  31051. },
  31052. enumerable: true,
  31053. configurable: true
  31054. });
  31055. Object.defineProperty(Mesh, "CAP_START", {
  31056. /**
  31057. * Mesh cap setting : one cap at the beginning of the mesh
  31058. */
  31059. get: function () {
  31060. return Mesh._CAP_START;
  31061. },
  31062. enumerable: true,
  31063. configurable: true
  31064. });
  31065. Object.defineProperty(Mesh, "CAP_END", {
  31066. /**
  31067. * Mesh cap setting : one cap at the end of the mesh
  31068. */
  31069. get: function () {
  31070. return Mesh._CAP_END;
  31071. },
  31072. enumerable: true,
  31073. configurable: true
  31074. });
  31075. Object.defineProperty(Mesh, "CAP_ALL", {
  31076. /**
  31077. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31078. */
  31079. get: function () {
  31080. return Mesh._CAP_ALL;
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31086. set: function (callback) {
  31087. if (this._onBeforeDrawObserver) {
  31088. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31089. }
  31090. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31091. },
  31092. enumerable: true,
  31093. configurable: true
  31094. });
  31095. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31096. get: function () {
  31097. return this._morphTargetManager;
  31098. },
  31099. set: function (value) {
  31100. if (this._morphTargetManager === value) {
  31101. return;
  31102. }
  31103. this._morphTargetManager = value;
  31104. this._syncGeometryWithMorphTargetManager();
  31105. },
  31106. enumerable: true,
  31107. configurable: true
  31108. });
  31109. Object.defineProperty(Mesh.prototype, "source", {
  31110. get: function () {
  31111. return this._source;
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31117. get: function () {
  31118. return this._unIndexed;
  31119. },
  31120. set: function (value) {
  31121. if (this._unIndexed !== value) {
  31122. this._unIndexed = value;
  31123. this._markSubMeshesAsAttributesDirty();
  31124. }
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. // Methods
  31130. /**
  31131. * Returns the string "Mesh".
  31132. */
  31133. Mesh.prototype.getClassName = function () {
  31134. return "Mesh";
  31135. };
  31136. /**
  31137. * Returns a string.
  31138. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31139. */
  31140. Mesh.prototype.toString = function (fullDetails) {
  31141. var ret = _super.prototype.toString.call(this, fullDetails);
  31142. ret += ", n vertices: " + this.getTotalVertices();
  31143. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31144. if (this.animations) {
  31145. for (var i = 0; i < this.animations.length; i++) {
  31146. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31147. }
  31148. }
  31149. if (fullDetails) {
  31150. if (this._geometry) {
  31151. var ib = this.getIndices();
  31152. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31153. if (vb && ib) {
  31154. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31155. }
  31156. }
  31157. else {
  31158. ret += ", flat shading: UNKNOWN";
  31159. }
  31160. }
  31161. return ret;
  31162. };
  31163. Mesh.prototype._unBindEffect = function () {
  31164. _super.prototype._unBindEffect.call(this);
  31165. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31166. var instance = _a[_i];
  31167. instance._unBindEffect();
  31168. }
  31169. };
  31170. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31171. /**
  31172. * True if the mesh has some Levels Of Details (LOD).
  31173. * Returns a boolean.
  31174. */
  31175. get: function () {
  31176. return this._LODLevels.length > 0;
  31177. },
  31178. enumerable: true,
  31179. configurable: true
  31180. });
  31181. /**
  31182. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31183. * @returns an array of {BABYLON.MeshLODLevel}
  31184. */
  31185. Mesh.prototype.getLODLevels = function () {
  31186. return this._LODLevels;
  31187. };
  31188. Mesh.prototype._sortLODLevels = function () {
  31189. this._LODLevels.sort(function (a, b) {
  31190. if (a.distance < b.distance) {
  31191. return 1;
  31192. }
  31193. if (a.distance > b.distance) {
  31194. return -1;
  31195. }
  31196. return 0;
  31197. });
  31198. };
  31199. /**
  31200. * Add a mesh as LOD level triggered at the given distance.
  31201. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31202. * @param {number} distance The distance from the center of the object to show this level
  31203. * @param {Mesh} mesh The mesh to be added as LOD level
  31204. * @return {Mesh} This mesh (for chaining)
  31205. */
  31206. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31207. if (mesh && mesh._masterMesh) {
  31208. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31209. return this;
  31210. }
  31211. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31212. this._LODLevels.push(level);
  31213. if (mesh) {
  31214. mesh._masterMesh = this;
  31215. }
  31216. this._sortLODLevels();
  31217. return this;
  31218. };
  31219. /**
  31220. * Returns the LOD level mesh at the passed distance or null if not found.
  31221. * It is related to the method `addLODLevel(distance, mesh)`.
  31222. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31223. * Returns an object Mesh or `null`.
  31224. */
  31225. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31226. for (var index = 0; index < this._LODLevels.length; index++) {
  31227. var level = this._LODLevels[index];
  31228. if (level.distance === distance) {
  31229. return level.mesh;
  31230. }
  31231. }
  31232. return null;
  31233. };
  31234. /**
  31235. * Remove a mesh from the LOD array
  31236. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31237. * @param {Mesh} mesh The mesh to be removed.
  31238. * @return {Mesh} This mesh (for chaining)
  31239. */
  31240. Mesh.prototype.removeLODLevel = function (mesh) {
  31241. for (var index = 0; index < this._LODLevels.length; index++) {
  31242. if (this._LODLevels[index].mesh === mesh) {
  31243. this._LODLevels.splice(index, 1);
  31244. if (mesh) {
  31245. mesh._masterMesh = null;
  31246. }
  31247. }
  31248. }
  31249. this._sortLODLevels();
  31250. return this;
  31251. };
  31252. /**
  31253. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31254. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31255. */
  31256. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31257. if (!this._LODLevels || this._LODLevels.length === 0) {
  31258. return this;
  31259. }
  31260. var bSphere;
  31261. if (boundingSphere) {
  31262. bSphere = boundingSphere;
  31263. }
  31264. else {
  31265. var boundingInfo = this.getBoundingInfo();
  31266. bSphere = boundingInfo.boundingSphere;
  31267. }
  31268. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31269. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31270. if (this.onLODLevelSelection) {
  31271. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31272. }
  31273. return this;
  31274. }
  31275. for (var index = 0; index < this._LODLevels.length; index++) {
  31276. var level = this._LODLevels[index];
  31277. if (level.distance < distanceToCamera) {
  31278. if (level.mesh) {
  31279. level.mesh._preActivate();
  31280. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31281. }
  31282. if (this.onLODLevelSelection) {
  31283. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31284. }
  31285. return level.mesh;
  31286. }
  31287. }
  31288. if (this.onLODLevelSelection) {
  31289. this.onLODLevelSelection(distanceToCamera, this, this);
  31290. }
  31291. return this;
  31292. };
  31293. Object.defineProperty(Mesh.prototype, "geometry", {
  31294. /**
  31295. * Returns the mesh internal Geometry object.
  31296. */
  31297. get: function () {
  31298. return this._geometry;
  31299. },
  31300. enumerable: true,
  31301. configurable: true
  31302. });
  31303. /**
  31304. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31305. */
  31306. Mesh.prototype.getTotalVertices = function () {
  31307. if (this._geometry === null || this._geometry === undefined) {
  31308. return 0;
  31309. }
  31310. return this._geometry.getTotalVertices();
  31311. };
  31312. /**
  31313. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31314. * 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.
  31315. * You can force the copy with forceCopy === true
  31316. * Returns null if the mesh has no geometry or no vertex buffer.
  31317. * Possible `kind` values :
  31318. * - BABYLON.VertexBuffer.PositionKind
  31319. * - BABYLON.VertexBuffer.UVKind
  31320. * - BABYLON.VertexBuffer.UV2Kind
  31321. * - BABYLON.VertexBuffer.UV3Kind
  31322. * - BABYLON.VertexBuffer.UV4Kind
  31323. * - BABYLON.VertexBuffer.UV5Kind
  31324. * - BABYLON.VertexBuffer.UV6Kind
  31325. * - BABYLON.VertexBuffer.ColorKind
  31326. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31327. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31328. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31329. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31330. */
  31331. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31332. if (!this._geometry) {
  31333. return null;
  31334. }
  31335. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31336. };
  31337. /**
  31338. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31339. * Returns `null` if the mesh has no geometry.
  31340. * Possible `kind` values :
  31341. * - BABYLON.VertexBuffer.PositionKind
  31342. * - BABYLON.VertexBuffer.UVKind
  31343. * - BABYLON.VertexBuffer.UV2Kind
  31344. * - BABYLON.VertexBuffer.UV3Kind
  31345. * - BABYLON.VertexBuffer.UV4Kind
  31346. * - BABYLON.VertexBuffer.UV5Kind
  31347. * - BABYLON.VertexBuffer.UV6Kind
  31348. * - BABYLON.VertexBuffer.ColorKind
  31349. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31350. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31351. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31352. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31353. */
  31354. Mesh.prototype.getVertexBuffer = function (kind) {
  31355. if (!this._geometry) {
  31356. return null;
  31357. }
  31358. return this._geometry.getVertexBuffer(kind);
  31359. };
  31360. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31361. if (!this._geometry) {
  31362. if (this._delayInfo) {
  31363. return this._delayInfo.indexOf(kind) !== -1;
  31364. }
  31365. return false;
  31366. }
  31367. return this._geometry.isVerticesDataPresent(kind);
  31368. };
  31369. /**
  31370. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31371. * Possible `kind` values :
  31372. * - BABYLON.VertexBuffer.PositionKind
  31373. * - BABYLON.VertexBuffer.UVKind
  31374. * - BABYLON.VertexBuffer.UV2Kind
  31375. * - BABYLON.VertexBuffer.UV3Kind
  31376. * - BABYLON.VertexBuffer.UV4Kind
  31377. * - BABYLON.VertexBuffer.UV5Kind
  31378. * - BABYLON.VertexBuffer.UV6Kind
  31379. * - BABYLON.VertexBuffer.ColorKind
  31380. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31381. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31382. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31383. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31384. */
  31385. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31386. if (!this._geometry) {
  31387. if (this._delayInfo) {
  31388. return this._delayInfo.indexOf(kind) !== -1;
  31389. }
  31390. return false;
  31391. }
  31392. return this._geometry.isVertexBufferUpdatable(kind);
  31393. };
  31394. /**
  31395. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31396. * Possible `kind` values :
  31397. * - BABYLON.VertexBuffer.PositionKind
  31398. * - BABYLON.VertexBuffer.UVKind
  31399. * - BABYLON.VertexBuffer.UV2Kind
  31400. * - BABYLON.VertexBuffer.UV3Kind
  31401. * - BABYLON.VertexBuffer.UV4Kind
  31402. * - BABYLON.VertexBuffer.UV5Kind
  31403. * - BABYLON.VertexBuffer.UV6Kind
  31404. * - BABYLON.VertexBuffer.ColorKind
  31405. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31406. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31407. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31408. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31409. */
  31410. Mesh.prototype.getVerticesDataKinds = function () {
  31411. if (!this._geometry) {
  31412. var result = new Array();
  31413. if (this._delayInfo) {
  31414. this._delayInfo.forEach(function (kind, index, array) {
  31415. result.push(kind);
  31416. });
  31417. }
  31418. return result;
  31419. }
  31420. return this._geometry.getVerticesDataKinds();
  31421. };
  31422. /**
  31423. * Returns a positive integer : the total number of indices in this mesh geometry.
  31424. * Returns zero if the mesh has no geometry.
  31425. */
  31426. Mesh.prototype.getTotalIndices = function () {
  31427. if (!this._geometry) {
  31428. return 0;
  31429. }
  31430. return this._geometry.getTotalIndices();
  31431. };
  31432. /**
  31433. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31434. * 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.
  31435. * Returns an empty array if the mesh has no geometry.
  31436. */
  31437. Mesh.prototype.getIndices = function (copyWhenShared) {
  31438. if (!this._geometry) {
  31439. return [];
  31440. }
  31441. return this._geometry.getIndices(copyWhenShared);
  31442. };
  31443. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31444. get: function () {
  31445. return this._masterMesh !== null && this._masterMesh !== undefined;
  31446. },
  31447. enumerable: true,
  31448. configurable: true
  31449. });
  31450. /**
  31451. * Determine if the current mesh is ready to be rendered
  31452. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31453. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31454. * @returns true if all associated assets are ready (material, textures, shaders)
  31455. */
  31456. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31457. if (completeCheck === void 0) { completeCheck = false; }
  31458. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31459. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31460. return false;
  31461. }
  31462. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31463. return false;
  31464. }
  31465. if (!this.subMeshes || this.subMeshes.length === 0) {
  31466. return true;
  31467. }
  31468. if (!completeCheck) {
  31469. return true;
  31470. }
  31471. var engine = this.getEngine();
  31472. var scene = this.getScene();
  31473. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31474. this.computeWorldMatrix();
  31475. var mat = this.material || scene.defaultMaterial;
  31476. if (mat) {
  31477. if (mat.storeEffectOnSubMeshes) {
  31478. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31479. var subMesh = _a[_i];
  31480. var effectiveMaterial = subMesh.getMaterial();
  31481. if (effectiveMaterial) {
  31482. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31483. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31484. return false;
  31485. }
  31486. }
  31487. else {
  31488. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31489. return false;
  31490. }
  31491. }
  31492. }
  31493. }
  31494. }
  31495. else {
  31496. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31497. return false;
  31498. }
  31499. }
  31500. }
  31501. // Shadows
  31502. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31503. var light = _c[_b];
  31504. var generator = light.getShadowGenerator();
  31505. if (generator) {
  31506. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31507. var subMesh = _e[_d];
  31508. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31509. return false;
  31510. }
  31511. }
  31512. }
  31513. }
  31514. // LOD
  31515. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31516. var lod = _g[_f];
  31517. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31518. return false;
  31519. }
  31520. }
  31521. return true;
  31522. };
  31523. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31524. /**
  31525. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31526. * This property is pertinent only for updatable parametric shapes.
  31527. */
  31528. get: function () {
  31529. return this._areNormalsFrozen;
  31530. },
  31531. enumerable: true,
  31532. configurable: true
  31533. });
  31534. /**
  31535. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31536. * It has no effect at all on other shapes.
  31537. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31538. * Returns the Mesh.
  31539. */
  31540. Mesh.prototype.freezeNormals = function () {
  31541. this._areNormalsFrozen = true;
  31542. return this;
  31543. };
  31544. /**
  31545. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31546. * It has no effect at all on other shapes.
  31547. * It reactivates the mesh normals computation if it was previously frozen.
  31548. * Returns the Mesh.
  31549. */
  31550. Mesh.prototype.unfreezeNormals = function () {
  31551. this._areNormalsFrozen = false;
  31552. return this;
  31553. };
  31554. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31555. /**
  31556. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31557. */
  31558. set: function (count) {
  31559. this._overridenInstanceCount = count;
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. // Methods
  31565. Mesh.prototype._preActivate = function () {
  31566. var sceneRenderId = this.getScene().getRenderId();
  31567. if (this._preActivateId === sceneRenderId) {
  31568. return this;
  31569. }
  31570. this._preActivateId = sceneRenderId;
  31571. this._visibleInstances = null;
  31572. return this;
  31573. };
  31574. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31575. if (this._visibleInstances) {
  31576. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31577. }
  31578. return this;
  31579. };
  31580. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31581. if (!this._visibleInstances) {
  31582. this._visibleInstances = {};
  31583. this._visibleInstances.defaultRenderId = renderId;
  31584. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31585. }
  31586. if (!this._visibleInstances[renderId]) {
  31587. this._visibleInstances[renderId] = new Array();
  31588. }
  31589. this._visibleInstances[renderId].push(instance);
  31590. return this;
  31591. };
  31592. /**
  31593. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31594. * This means the mesh underlying bounding box and sphere are recomputed.
  31595. * Returns the Mesh.
  31596. */
  31597. Mesh.prototype.refreshBoundingInfo = function () {
  31598. return this._refreshBoundingInfo(false);
  31599. };
  31600. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31601. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31602. return this;
  31603. }
  31604. var data = this._getPositionData(applySkeleton);
  31605. if (data) {
  31606. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31607. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31608. }
  31609. if (this.subMeshes) {
  31610. for (var index = 0; index < this.subMeshes.length; index++) {
  31611. this.subMeshes[index].refreshBoundingInfo();
  31612. }
  31613. }
  31614. this._updateBoundingInfo();
  31615. return this;
  31616. };
  31617. Mesh.prototype._getPositionData = function (applySkeleton) {
  31618. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31619. if (data && applySkeleton && this.skeleton) {
  31620. data = BABYLON.Tools.Slice(data);
  31621. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31622. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31623. if (matricesWeightsData && matricesIndicesData) {
  31624. var needExtras = this.numBoneInfluencers > 4;
  31625. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31626. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31627. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31628. var tempVector = BABYLON.Tmp.Vector3[0];
  31629. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31630. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31631. var matWeightIdx = 0;
  31632. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31633. finalMatrix.reset();
  31634. var inf;
  31635. var weight;
  31636. for (inf = 0; inf < 4; inf++) {
  31637. weight = matricesWeightsData[matWeightIdx + inf];
  31638. if (weight <= 0)
  31639. break;
  31640. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31641. finalMatrix.addToSelf(tempMatrix);
  31642. }
  31643. if (needExtras) {
  31644. for (inf = 0; inf < 4; inf++) {
  31645. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31646. if (weight <= 0)
  31647. break;
  31648. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31649. finalMatrix.addToSelf(tempMatrix);
  31650. }
  31651. }
  31652. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31653. tempVector.toArray(data, index);
  31654. }
  31655. }
  31656. }
  31657. return data;
  31658. };
  31659. Mesh.prototype._createGlobalSubMesh = function (force) {
  31660. var totalVertices = this.getTotalVertices();
  31661. if (!totalVertices || !this.getIndices()) {
  31662. return null;
  31663. }
  31664. // Check if we need to recreate the submeshes
  31665. if (this.subMeshes && this.subMeshes.length > 0) {
  31666. var ib = this.getIndices();
  31667. if (!ib) {
  31668. return null;
  31669. }
  31670. var totalIndices = ib.length;
  31671. var needToRecreate = false;
  31672. if (force) {
  31673. needToRecreate = true;
  31674. }
  31675. else {
  31676. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31677. var submesh = _a[_i];
  31678. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31679. needToRecreate = true;
  31680. break;
  31681. }
  31682. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31683. needToRecreate = true;
  31684. break;
  31685. }
  31686. }
  31687. }
  31688. if (!needToRecreate) {
  31689. return this.subMeshes[0];
  31690. }
  31691. }
  31692. this.releaseSubMeshes();
  31693. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31694. };
  31695. Mesh.prototype.subdivide = function (count) {
  31696. if (count < 1) {
  31697. return;
  31698. }
  31699. var totalIndices = this.getTotalIndices();
  31700. var subdivisionSize = (totalIndices / count) | 0;
  31701. var offset = 0;
  31702. // Ensure that subdivisionSize is a multiple of 3
  31703. while (subdivisionSize % 3 !== 0) {
  31704. subdivisionSize++;
  31705. }
  31706. this.releaseSubMeshes();
  31707. for (var index = 0; index < count; index++) {
  31708. if (offset >= totalIndices) {
  31709. break;
  31710. }
  31711. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31712. offset += subdivisionSize;
  31713. }
  31714. this.synchronizeInstances();
  31715. };
  31716. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31717. if (updatable === void 0) { updatable = false; }
  31718. if (!this._geometry) {
  31719. var vertexData = new BABYLON.VertexData();
  31720. vertexData.set(data, kind);
  31721. var scene = this.getScene();
  31722. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31723. }
  31724. else {
  31725. this._geometry.setVerticesData(kind, data, updatable, stride);
  31726. }
  31727. return this;
  31728. };
  31729. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31730. if (updatable === void 0) { updatable = true; }
  31731. var vb = this.getVertexBuffer(kind);
  31732. if (!vb || vb.isUpdatable() === updatable) {
  31733. return;
  31734. }
  31735. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31736. };
  31737. /**
  31738. * Sets the mesh VertexBuffer.
  31739. * Returns the Mesh.
  31740. */
  31741. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31742. if (!this._geometry) {
  31743. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31744. }
  31745. this._geometry.setVerticesBuffer(buffer);
  31746. return this;
  31747. };
  31748. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31749. if (!this._geometry) {
  31750. return this;
  31751. }
  31752. if (!makeItUnique) {
  31753. this._geometry.updateVerticesData(kind, data, updateExtends);
  31754. }
  31755. else {
  31756. this.makeGeometryUnique();
  31757. this.updateVerticesData(kind, data, updateExtends, false);
  31758. }
  31759. return this;
  31760. };
  31761. /**
  31762. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31763. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31764. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31765. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31766. * Returns the Mesh.
  31767. */
  31768. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31769. if (computeNormals === void 0) { computeNormals = true; }
  31770. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31771. if (!positions) {
  31772. return this;
  31773. }
  31774. positionFunction(positions);
  31775. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31776. if (computeNormals) {
  31777. var indices = this.getIndices();
  31778. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31779. if (!normals) {
  31780. return this;
  31781. }
  31782. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31783. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31784. }
  31785. return this;
  31786. };
  31787. /**
  31788. * Creates a un-shared specific occurence of the geometry for the mesh.
  31789. * Returns the Mesh.
  31790. */
  31791. Mesh.prototype.makeGeometryUnique = function () {
  31792. if (!this._geometry) {
  31793. return this;
  31794. }
  31795. var oldGeometry = this._geometry;
  31796. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31797. oldGeometry.releaseForMesh(this, true);
  31798. geometry.applyToMesh(this);
  31799. return this;
  31800. };
  31801. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31802. if (totalVertices === void 0) { totalVertices = null; }
  31803. if (updatable === void 0) { updatable = false; }
  31804. if (!this._geometry) {
  31805. var vertexData = new BABYLON.VertexData();
  31806. vertexData.indices = indices;
  31807. var scene = this.getScene();
  31808. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31809. }
  31810. else {
  31811. this._geometry.setIndices(indices, totalVertices, updatable);
  31812. }
  31813. return this;
  31814. };
  31815. /**
  31816. * Update the current index buffer
  31817. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31818. * Returns the Mesh.
  31819. */
  31820. Mesh.prototype.updateIndices = function (indices, offset) {
  31821. if (!this._geometry) {
  31822. return this;
  31823. }
  31824. this._geometry.updateIndices(indices, offset);
  31825. return this;
  31826. };
  31827. /**
  31828. * Invert the geometry to move from a right handed system to a left handed one.
  31829. * Returns the Mesh.
  31830. */
  31831. Mesh.prototype.toLeftHanded = function () {
  31832. if (!this._geometry) {
  31833. return this;
  31834. }
  31835. this._geometry.toLeftHanded();
  31836. return this;
  31837. };
  31838. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31839. if (!this._geometry) {
  31840. return this;
  31841. }
  31842. var engine = this.getScene().getEngine();
  31843. // Wireframe
  31844. var indexToBind;
  31845. if (this._unIndexed) {
  31846. indexToBind = null;
  31847. }
  31848. else {
  31849. switch (fillMode) {
  31850. case BABYLON.Material.PointFillMode:
  31851. indexToBind = null;
  31852. break;
  31853. case BABYLON.Material.WireFrameFillMode:
  31854. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31855. break;
  31856. default:
  31857. case BABYLON.Material.TriangleFillMode:
  31858. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31859. break;
  31860. }
  31861. }
  31862. // VBOs
  31863. this._geometry._bind(effect, indexToBind);
  31864. return this;
  31865. };
  31866. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31867. if (alternate === void 0) { alternate = false; }
  31868. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31869. return this;
  31870. }
  31871. this.onBeforeDrawObservable.notifyObservers(this);
  31872. var scene = this.getScene();
  31873. var engine = scene.getEngine();
  31874. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31875. // or triangles as points
  31876. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31877. }
  31878. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31879. // Triangles as wireframe
  31880. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31881. }
  31882. else {
  31883. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31884. }
  31885. if (scene._isAlternateRenderingEnabled && !alternate) {
  31886. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31887. if (!effect || !scene.activeCamera) {
  31888. return this;
  31889. }
  31890. scene._switchToAlternateCameraConfiguration(true);
  31891. this._effectiveMaterial.bindView(effect);
  31892. this._effectiveMaterial.bindViewProjection(effect);
  31893. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31894. this._draw(subMesh, fillMode, instancesCount, true);
  31895. engine.setViewport(scene.activeCamera.viewport);
  31896. scene._switchToAlternateCameraConfiguration(false);
  31897. this._effectiveMaterial.bindView(effect);
  31898. this._effectiveMaterial.bindViewProjection(effect);
  31899. }
  31900. return this;
  31901. };
  31902. /**
  31903. * Registers for this mesh a javascript function called just before the rendering process.
  31904. * This function is passed the current mesh.
  31905. * Return the Mesh.
  31906. */
  31907. Mesh.prototype.registerBeforeRender = function (func) {
  31908. this.onBeforeRenderObservable.add(func);
  31909. return this;
  31910. };
  31911. /**
  31912. * Disposes a previously registered javascript function called before the rendering.
  31913. * This function is passed the current mesh.
  31914. * Returns the Mesh.
  31915. */
  31916. Mesh.prototype.unregisterBeforeRender = function (func) {
  31917. this.onBeforeRenderObservable.removeCallback(func);
  31918. return this;
  31919. };
  31920. /**
  31921. * Registers for this mesh a javascript function called just after the rendering is complete.
  31922. * This function is passed the current mesh.
  31923. * Returns the Mesh.
  31924. */
  31925. Mesh.prototype.registerAfterRender = function (func) {
  31926. this.onAfterRenderObservable.add(func);
  31927. return this;
  31928. };
  31929. /**
  31930. * Disposes a previously registered javascript function called after the rendering.
  31931. * This function is passed the current mesh.
  31932. * Return the Mesh.
  31933. */
  31934. Mesh.prototype.unregisterAfterRender = function (func) {
  31935. this.onAfterRenderObservable.removeCallback(func);
  31936. return this;
  31937. };
  31938. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31939. var scene = this.getScene();
  31940. this._batchCache.mustReturn = false;
  31941. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31942. this._batchCache.visibleInstances[subMeshId] = null;
  31943. if (this._visibleInstances) {
  31944. var currentRenderId = scene.getRenderId();
  31945. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31946. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31947. var selfRenderId = this._renderId;
  31948. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31949. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31950. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31951. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31952. }
  31953. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31954. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31955. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31956. this._batchCache.mustReturn = true;
  31957. return this._batchCache;
  31958. }
  31959. if (currentRenderId !== selfRenderId) {
  31960. this._batchCache.renderSelf[subMeshId] = false;
  31961. }
  31962. }
  31963. this._renderIdForInstances[subMeshId] = currentRenderId;
  31964. }
  31965. return this._batchCache;
  31966. };
  31967. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31968. var visibleInstances = batch.visibleInstances[subMesh._id];
  31969. if (!visibleInstances) {
  31970. return this;
  31971. }
  31972. var matricesCount = visibleInstances.length + 1;
  31973. var bufferSize = matricesCount * 16 * 4;
  31974. var currentInstancesBufferSize = this._instancesBufferSize;
  31975. var instancesBuffer = this._instancesBuffer;
  31976. while (this._instancesBufferSize < bufferSize) {
  31977. this._instancesBufferSize *= 2;
  31978. }
  31979. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31980. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31981. }
  31982. var offset = 0;
  31983. var instancesCount = 0;
  31984. var world = this.getWorldMatrix();
  31985. if (batch.renderSelf[subMesh._id]) {
  31986. world.copyToArray(this._instancesData, offset);
  31987. offset += 16;
  31988. instancesCount++;
  31989. }
  31990. if (visibleInstances) {
  31991. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31992. var instance = visibleInstances[instanceIndex];
  31993. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31994. offset += 16;
  31995. instancesCount++;
  31996. }
  31997. }
  31998. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31999. if (instancesBuffer) {
  32000. instancesBuffer.dispose();
  32001. }
  32002. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32003. this._instancesBuffer = instancesBuffer;
  32004. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32005. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32006. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32007. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32008. }
  32009. else {
  32010. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32011. }
  32012. this._bind(subMesh, effect, fillMode);
  32013. this._draw(subMesh, fillMode, instancesCount);
  32014. engine.unbindInstanceAttributes();
  32015. return this;
  32016. };
  32017. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32018. var scene = this.getScene();
  32019. var engine = scene.getEngine();
  32020. if (hardwareInstancedRendering) {
  32021. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32022. }
  32023. else {
  32024. if (batch.renderSelf[subMesh._id]) {
  32025. // Draw
  32026. if (onBeforeDraw) {
  32027. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32028. }
  32029. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32030. }
  32031. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32032. if (visibleInstancesForSubMesh) {
  32033. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32034. var instance = visibleInstancesForSubMesh[instanceIndex];
  32035. // World
  32036. var world = instance.getWorldMatrix();
  32037. if (onBeforeDraw) {
  32038. onBeforeDraw(true, world, effectiveMaterial);
  32039. }
  32040. // Draw
  32041. this._draw(subMesh, fillMode);
  32042. }
  32043. }
  32044. }
  32045. return this;
  32046. };
  32047. /**
  32048. * Triggers the draw call for the mesh.
  32049. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32050. * Returns the Mesh.
  32051. */
  32052. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32053. this._checkOcclusionQuery();
  32054. if (this._isOccluded) {
  32055. return this;
  32056. }
  32057. var scene = this.getScene();
  32058. // Managing instances
  32059. var batch = this._getInstancesRenderList(subMesh._id);
  32060. if (batch.mustReturn) {
  32061. return this;
  32062. }
  32063. // Checking geometry state
  32064. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32065. return this;
  32066. }
  32067. this.onBeforeRenderObservable.notifyObservers(this);
  32068. var engine = scene.getEngine();
  32069. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32070. // Material
  32071. var material = subMesh.getMaterial();
  32072. if (!material) {
  32073. return this;
  32074. }
  32075. this._effectiveMaterial = material;
  32076. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32077. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32078. return this;
  32079. }
  32080. }
  32081. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32082. return this;
  32083. }
  32084. // Alpha mode
  32085. if (enableAlphaMode) {
  32086. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32087. }
  32088. // Outline - step 1
  32089. var savedDepthWrite = engine.getDepthWrite();
  32090. if (this.renderOutline) {
  32091. engine.setDepthWrite(false);
  32092. scene.getOutlineRenderer().render(subMesh, batch);
  32093. engine.setDepthWrite(savedDepthWrite);
  32094. }
  32095. var effect;
  32096. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32097. effect = subMesh.effect;
  32098. }
  32099. else {
  32100. effect = this._effectiveMaterial.getEffect();
  32101. }
  32102. if (!effect) {
  32103. return this;
  32104. }
  32105. var sideOrientation = this.overrideMaterialSideOrientation;
  32106. if (sideOrientation == null) {
  32107. sideOrientation = this._effectiveMaterial.sideOrientation;
  32108. if (this._getWorldMatrixDeterminant() < 0) {
  32109. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32110. }
  32111. }
  32112. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32113. if (this._effectiveMaterial.forceDepthWrite) {
  32114. engine.setDepthWrite(true);
  32115. }
  32116. // Bind
  32117. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32118. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32119. this._bind(subMesh, effect, fillMode);
  32120. }
  32121. var world = this.getWorldMatrix();
  32122. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32123. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32124. }
  32125. else {
  32126. this._effectiveMaterial.bind(world, this);
  32127. }
  32128. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32129. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32130. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32131. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32132. }
  32133. // Draw
  32134. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32135. // Unbind
  32136. this._effectiveMaterial.unbind();
  32137. // Outline - step 2
  32138. if (this.renderOutline && savedDepthWrite) {
  32139. engine.setDepthWrite(true);
  32140. engine.setColorWrite(false);
  32141. scene.getOutlineRenderer().render(subMesh, batch);
  32142. engine.setColorWrite(true);
  32143. }
  32144. // Overlay
  32145. if (this.renderOverlay) {
  32146. var currentMode = engine.getAlphaMode();
  32147. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32148. scene.getOutlineRenderer().render(subMesh, batch, true);
  32149. engine.setAlphaMode(currentMode);
  32150. }
  32151. this.onAfterRenderObservable.notifyObservers(this);
  32152. return this;
  32153. };
  32154. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32155. if (isInstance && effectiveMaterial) {
  32156. effectiveMaterial.bindOnlyWorldMatrix(world);
  32157. }
  32158. };
  32159. /**
  32160. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32161. */
  32162. Mesh.prototype.getEmittedParticleSystems = function () {
  32163. var results = new Array();
  32164. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32165. var particleSystem = this.getScene().particleSystems[index];
  32166. if (particleSystem.emitter === this) {
  32167. results.push(particleSystem);
  32168. }
  32169. }
  32170. return results;
  32171. };
  32172. /**
  32173. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32174. */
  32175. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32176. var results = new Array();
  32177. var descendants = this.getDescendants();
  32178. descendants.push(this);
  32179. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32180. var particleSystem = this.getScene().particleSystems[index];
  32181. var emitter = particleSystem.emitter;
  32182. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32183. results.push(particleSystem);
  32184. }
  32185. }
  32186. return results;
  32187. };
  32188. Mesh.prototype._checkDelayState = function () {
  32189. var scene = this.getScene();
  32190. if (this._geometry) {
  32191. this._geometry.load(scene);
  32192. }
  32193. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32195. this._queueLoad(scene);
  32196. }
  32197. return this;
  32198. };
  32199. Mesh.prototype._queueLoad = function (scene) {
  32200. var _this = this;
  32201. scene._addPendingData(this);
  32202. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32203. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32204. if (data instanceof ArrayBuffer) {
  32205. _this._delayLoadingFunction(data, _this);
  32206. }
  32207. else {
  32208. _this._delayLoadingFunction(JSON.parse(data), _this);
  32209. }
  32210. _this.instances.forEach(function (instance) {
  32211. instance._syncSubMeshes();
  32212. });
  32213. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32214. scene._removePendingData(_this);
  32215. }, function () { }, scene.database, getBinaryData);
  32216. return this;
  32217. };
  32218. /**
  32219. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32220. */
  32221. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32222. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32223. return false;
  32224. }
  32225. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32226. return false;
  32227. }
  32228. this._checkDelayState();
  32229. return true;
  32230. };
  32231. /**
  32232. * Sets the mesh material by the material or multiMaterial `id` property.
  32233. * The material `id` is a string identifying the material or the multiMaterial.
  32234. * This method returns the Mesh.
  32235. */
  32236. Mesh.prototype.setMaterialByID = function (id) {
  32237. var materials = this.getScene().materials;
  32238. var index;
  32239. for (index = materials.length - 1; index > -1; index--) {
  32240. if (materials[index].id === id) {
  32241. this.material = materials[index];
  32242. return this;
  32243. }
  32244. }
  32245. // Multi
  32246. var multiMaterials = this.getScene().multiMaterials;
  32247. for (index = multiMaterials.length - 1; index > -1; index--) {
  32248. if (multiMaterials[index].id === id) {
  32249. this.material = multiMaterials[index];
  32250. return this;
  32251. }
  32252. }
  32253. return this;
  32254. };
  32255. /**
  32256. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32257. */
  32258. Mesh.prototype.getAnimatables = function () {
  32259. var results = new Array();
  32260. if (this.material) {
  32261. results.push(this.material);
  32262. }
  32263. if (this.skeleton) {
  32264. results.push(this.skeleton);
  32265. }
  32266. return results;
  32267. };
  32268. /**
  32269. * Modifies the mesh geometry according to the passed transformation matrix.
  32270. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32271. * The mesh normals are modified accordingly the same transformation.
  32272. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32273. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32274. * Returns the Mesh.
  32275. */
  32276. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32277. // Position
  32278. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32279. return this;
  32280. }
  32281. var submeshes = this.subMeshes.splice(0);
  32282. this._resetPointsArrayCache();
  32283. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32284. var temp = new Array();
  32285. var index;
  32286. for (index = 0; index < data.length; index += 3) {
  32287. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32288. }
  32289. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32290. // Normals
  32291. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32292. return this;
  32293. }
  32294. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32295. temp = [];
  32296. for (index = 0; index < data.length; index += 3) {
  32297. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32298. }
  32299. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32300. // flip faces?
  32301. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32302. this.flipFaces();
  32303. }
  32304. // Restore submeshes
  32305. this.releaseSubMeshes();
  32306. this.subMeshes = submeshes;
  32307. return this;
  32308. };
  32309. /**
  32310. * Modifies the mesh geometry according to its own current World Matrix.
  32311. * The mesh World Matrix is then reset.
  32312. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32313. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32314. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32315. * Returns the Mesh.
  32316. */
  32317. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32318. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32319. this.scaling.copyFromFloats(1, 1, 1);
  32320. this.position.copyFromFloats(0, 0, 0);
  32321. this.rotation.copyFromFloats(0, 0, 0);
  32322. //only if quaternion is already set
  32323. if (this.rotationQuaternion) {
  32324. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32325. }
  32326. this._worldMatrix = BABYLON.Matrix.Identity();
  32327. return this;
  32328. };
  32329. Object.defineProperty(Mesh.prototype, "_positions", {
  32330. // Cache
  32331. get: function () {
  32332. if (this._geometry) {
  32333. return this._geometry._positions;
  32334. }
  32335. return null;
  32336. },
  32337. enumerable: true,
  32338. configurable: true
  32339. });
  32340. Mesh.prototype._resetPointsArrayCache = function () {
  32341. if (this._geometry) {
  32342. this._geometry._resetPointsArrayCache();
  32343. }
  32344. return this;
  32345. };
  32346. Mesh.prototype._generatePointsArray = function () {
  32347. if (this._geometry) {
  32348. return this._geometry._generatePointsArray();
  32349. }
  32350. return false;
  32351. };
  32352. /**
  32353. * Returns a new Mesh object generated from the current mesh properties.
  32354. * This method must not get confused with createInstance().
  32355. * The parameter `name` is a string, the name given to the new mesh.
  32356. * The optional parameter `newParent` can be any Node object (default `null`).
  32357. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32358. * 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.
  32359. */
  32360. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32361. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32362. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32363. };
  32364. /**
  32365. * Releases resources associated with this mesh.
  32366. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32367. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32368. */
  32369. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32370. var _this = this;
  32371. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32372. this.morphTargetManager = null;
  32373. if (this._geometry) {
  32374. this._geometry.releaseForMesh(this, true);
  32375. }
  32376. // Sources
  32377. var meshes = this.getScene().meshes;
  32378. meshes.forEach(function (abstractMesh) {
  32379. var mesh = abstractMesh;
  32380. if (mesh._source && mesh._source === _this) {
  32381. mesh._source = null;
  32382. }
  32383. });
  32384. this._source = null;
  32385. // Instances
  32386. if (this._instancesBuffer) {
  32387. this._instancesBuffer.dispose();
  32388. this._instancesBuffer = null;
  32389. }
  32390. while (this.instances.length) {
  32391. this.instances[0].dispose();
  32392. }
  32393. // Effect layers.
  32394. var effectLayers = this.getScene().effectLayers;
  32395. for (var i = 0; i < effectLayers.length; i++) {
  32396. var effectLayer = effectLayers[i];
  32397. if (effectLayer) {
  32398. effectLayer._disposeMesh(this);
  32399. }
  32400. }
  32401. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32402. };
  32403. /**
  32404. * Modifies the mesh geometry according to a displacement map.
  32405. * 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.
  32406. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32407. * This method returns nothing.
  32408. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32409. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32410. * 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.
  32411. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32412. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32413. *
  32414. * Returns the Mesh.
  32415. */
  32416. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32417. var _this = this;
  32418. var scene = this.getScene();
  32419. var onload = function (img) {
  32420. // Getting height map data
  32421. var canvas = document.createElement("canvas");
  32422. var context = canvas.getContext("2d");
  32423. var heightMapWidth = img.width;
  32424. var heightMapHeight = img.height;
  32425. canvas.width = heightMapWidth;
  32426. canvas.height = heightMapHeight;
  32427. context.drawImage(img, 0, 0);
  32428. // Create VertexData from map data
  32429. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32430. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32431. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32432. //execute success callback, if set
  32433. if (onSuccess) {
  32434. onSuccess(_this);
  32435. }
  32436. };
  32437. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32438. return this;
  32439. };
  32440. /**
  32441. * Modifies the mesh geometry according to a displacementMap buffer.
  32442. * 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.
  32443. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32444. * This method returns nothing.
  32445. * 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.
  32446. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32447. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32448. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32449. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32450. *
  32451. * Returns the Mesh.
  32452. */
  32453. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32454. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32455. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32456. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32457. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32458. return this;
  32459. }
  32460. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32461. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32462. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32463. var position = BABYLON.Vector3.Zero();
  32464. var normal = BABYLON.Vector3.Zero();
  32465. var uv = BABYLON.Vector2.Zero();
  32466. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32467. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32468. for (var index = 0; index < positions.length; index += 3) {
  32469. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32470. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32471. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32472. // Compute height
  32473. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32474. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32475. var pos = (u + v * heightMapWidth) * 4;
  32476. var r = buffer[pos] / 255.0;
  32477. var g = buffer[pos + 1] / 255.0;
  32478. var b = buffer[pos + 2] / 255.0;
  32479. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32480. normal.normalize();
  32481. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32482. position = position.add(normal);
  32483. position.toArray(positions, index);
  32484. }
  32485. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32486. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32487. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32488. return this;
  32489. };
  32490. /**
  32491. * Modify the mesh to get a flat shading rendering.
  32492. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32493. * This method returns the Mesh.
  32494. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32495. */
  32496. Mesh.prototype.convertToFlatShadedMesh = function () {
  32497. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32498. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32499. var kinds = this.getVerticesDataKinds();
  32500. var vbs = {};
  32501. var data = {};
  32502. var newdata = {};
  32503. var updatableNormals = false;
  32504. var kindIndex;
  32505. var kind;
  32506. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32507. kind = kinds[kindIndex];
  32508. var vertexBuffer = this.getVertexBuffer(kind);
  32509. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32510. updatableNormals = vertexBuffer.isUpdatable();
  32511. kinds.splice(kindIndex, 1);
  32512. kindIndex--;
  32513. continue;
  32514. }
  32515. vbs[kind] = vertexBuffer;
  32516. data[kind] = vbs[kind].getData();
  32517. newdata[kind] = [];
  32518. }
  32519. // Save previous submeshes
  32520. var previousSubmeshes = this.subMeshes.slice(0);
  32521. var indices = this.getIndices();
  32522. var totalIndices = this.getTotalIndices();
  32523. // Generating unique vertices per face
  32524. var index;
  32525. for (index = 0; index < totalIndices; index++) {
  32526. var vertexIndex = indices[index];
  32527. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32528. kind = kinds[kindIndex];
  32529. var stride = vbs[kind].getStrideSize();
  32530. for (var offset = 0; offset < stride; offset++) {
  32531. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32532. }
  32533. }
  32534. }
  32535. // Updating faces & normal
  32536. var normals = [];
  32537. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32538. for (index = 0; index < totalIndices; index += 3) {
  32539. indices[index] = index;
  32540. indices[index + 1] = index + 1;
  32541. indices[index + 2] = index + 2;
  32542. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32543. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32544. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32545. var p1p2 = p1.subtract(p2);
  32546. var p3p2 = p3.subtract(p2);
  32547. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32548. // Store same normals for every vertex
  32549. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32550. normals.push(normal.x);
  32551. normals.push(normal.y);
  32552. normals.push(normal.z);
  32553. }
  32554. }
  32555. this.setIndices(indices);
  32556. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32557. // Updating vertex buffers
  32558. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32559. kind = kinds[kindIndex];
  32560. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32561. }
  32562. // Updating submeshes
  32563. this.releaseSubMeshes();
  32564. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32565. var previousOne = previousSubmeshes[submeshIndex];
  32566. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32567. }
  32568. this.synchronizeInstances();
  32569. return this;
  32570. };
  32571. /**
  32572. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32573. * In other words, more vertices, no more indices and a single bigger VBO.
  32574. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32575. * Returns the Mesh.
  32576. */
  32577. Mesh.prototype.convertToUnIndexedMesh = function () {
  32578. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32579. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32580. var kinds = this.getVerticesDataKinds();
  32581. var vbs = {};
  32582. var data = {};
  32583. var newdata = {};
  32584. var kindIndex;
  32585. var kind;
  32586. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32587. kind = kinds[kindIndex];
  32588. var vertexBuffer = this.getVertexBuffer(kind);
  32589. vbs[kind] = vertexBuffer;
  32590. data[kind] = vbs[kind].getData();
  32591. newdata[kind] = [];
  32592. }
  32593. // Save previous submeshes
  32594. var previousSubmeshes = this.subMeshes.slice(0);
  32595. var indices = this.getIndices();
  32596. var totalIndices = this.getTotalIndices();
  32597. // Generating unique vertices per face
  32598. var index;
  32599. for (index = 0; index < totalIndices; index++) {
  32600. var vertexIndex = indices[index];
  32601. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32602. kind = kinds[kindIndex];
  32603. var stride = vbs[kind].getStrideSize();
  32604. for (var offset = 0; offset < stride; offset++) {
  32605. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32606. }
  32607. }
  32608. }
  32609. // Updating indices
  32610. for (index = 0; index < totalIndices; index += 3) {
  32611. indices[index] = index;
  32612. indices[index + 1] = index + 1;
  32613. indices[index + 2] = index + 2;
  32614. }
  32615. this.setIndices(indices);
  32616. // Updating vertex buffers
  32617. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32618. kind = kinds[kindIndex];
  32619. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32620. }
  32621. // Updating submeshes
  32622. this.releaseSubMeshes();
  32623. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32624. var previousOne = previousSubmeshes[submeshIndex];
  32625. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32626. }
  32627. this._unIndexed = true;
  32628. this.synchronizeInstances();
  32629. return this;
  32630. };
  32631. /**
  32632. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32633. * This method returns the Mesh.
  32634. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32635. */
  32636. Mesh.prototype.flipFaces = function (flipNormals) {
  32637. if (flipNormals === void 0) { flipNormals = false; }
  32638. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32639. var i;
  32640. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32641. for (i = 0; i < vertex_data.normals.length; i++) {
  32642. vertex_data.normals[i] *= -1;
  32643. }
  32644. }
  32645. if (vertex_data.indices) {
  32646. var temp;
  32647. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32648. // reassign indices
  32649. temp = vertex_data.indices[i + 1];
  32650. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32651. vertex_data.indices[i + 2] = temp;
  32652. }
  32653. }
  32654. vertex_data.applyToMesh(this);
  32655. return this;
  32656. };
  32657. // Instances
  32658. /**
  32659. * Creates a new InstancedMesh object from the mesh model.
  32660. * An instance shares the same properties and the same material than its model.
  32661. * Only these properties of each instance can then be set individually :
  32662. * - position
  32663. * - rotation
  32664. * - rotationQuaternion
  32665. * - setPivotMatrix
  32666. * - scaling
  32667. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32668. * Warning : this method is not supported for Line mesh and LineSystem
  32669. */
  32670. Mesh.prototype.createInstance = function (name) {
  32671. return new BABYLON.InstancedMesh(name, this);
  32672. };
  32673. /**
  32674. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32675. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32676. * This method returns the Mesh.
  32677. */
  32678. Mesh.prototype.synchronizeInstances = function () {
  32679. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32680. var instance = this.instances[instanceIndex];
  32681. instance._syncSubMeshes();
  32682. }
  32683. return this;
  32684. };
  32685. /**
  32686. * Simplify the mesh according to the given array of settings.
  32687. * Function will return immediately and will simplify async. It returns the Mesh.
  32688. * @param settings a collection of simplification settings.
  32689. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32690. * @param type the type of simplification to run.
  32691. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32692. */
  32693. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32694. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32695. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32696. this.getScene().simplificationQueue.addTask({
  32697. settings: settings,
  32698. parallelProcessing: parallelProcessing,
  32699. mesh: this,
  32700. simplificationType: simplificationType,
  32701. successCallback: successCallback
  32702. });
  32703. return this;
  32704. };
  32705. /**
  32706. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32707. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32708. * This should be used together with the simplification to avoid disappearing triangles.
  32709. * Returns the Mesh.
  32710. * @param successCallback an optional success callback to be called after the optimization finished.
  32711. */
  32712. Mesh.prototype.optimizeIndices = function (successCallback) {
  32713. var _this = this;
  32714. var indices = this.getIndices();
  32715. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32716. if (!positions || !indices) {
  32717. return this;
  32718. }
  32719. var vectorPositions = new Array();
  32720. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32721. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32722. }
  32723. var dupes = new Array();
  32724. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32725. var realPos = vectorPositions.length - 1 - iteration;
  32726. var testedPosition = vectorPositions[realPos];
  32727. for (var j = 0; j < realPos; ++j) {
  32728. var againstPosition = vectorPositions[j];
  32729. if (testedPosition.equals(againstPosition)) {
  32730. dupes[realPos] = j;
  32731. break;
  32732. }
  32733. }
  32734. }, function () {
  32735. for (var i = 0; i < indices.length; ++i) {
  32736. indices[i] = dupes[indices[i]] || indices[i];
  32737. }
  32738. //indices are now reordered
  32739. var originalSubMeshes = _this.subMeshes.slice(0);
  32740. _this.setIndices(indices);
  32741. _this.subMeshes = originalSubMeshes;
  32742. if (successCallback) {
  32743. successCallback(_this);
  32744. }
  32745. });
  32746. return this;
  32747. };
  32748. Mesh.prototype.serialize = function (serializationObject) {
  32749. serializationObject.name = this.name;
  32750. serializationObject.id = this.id;
  32751. serializationObject.type = this.getClassName();
  32752. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32753. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32754. }
  32755. serializationObject.position = this.position.asArray();
  32756. if (this.rotationQuaternion) {
  32757. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32758. }
  32759. else if (this.rotation) {
  32760. serializationObject.rotation = this.rotation.asArray();
  32761. }
  32762. serializationObject.scaling = this.scaling.asArray();
  32763. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32764. serializationObject.isEnabled = this.isEnabled(false);
  32765. serializationObject.isVisible = this.isVisible;
  32766. serializationObject.infiniteDistance = this.infiniteDistance;
  32767. serializationObject.pickable = this.isPickable;
  32768. serializationObject.receiveShadows = this.receiveShadows;
  32769. serializationObject.billboardMode = this.billboardMode;
  32770. serializationObject.visibility = this.visibility;
  32771. serializationObject.checkCollisions = this.checkCollisions;
  32772. serializationObject.isBlocker = this.isBlocker;
  32773. // Parent
  32774. if (this.parent) {
  32775. serializationObject.parentId = this.parent.id;
  32776. }
  32777. // Geometry
  32778. serializationObject.isUnIndexed = this.isUnIndexed;
  32779. var geometry = this._geometry;
  32780. if (geometry) {
  32781. var geometryId = geometry.id;
  32782. serializationObject.geometryId = geometryId;
  32783. // SubMeshes
  32784. serializationObject.subMeshes = [];
  32785. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32786. var subMesh = this.subMeshes[subIndex];
  32787. serializationObject.subMeshes.push({
  32788. materialIndex: subMesh.materialIndex,
  32789. verticesStart: subMesh.verticesStart,
  32790. verticesCount: subMesh.verticesCount,
  32791. indexStart: subMesh.indexStart,
  32792. indexCount: subMesh.indexCount
  32793. });
  32794. }
  32795. }
  32796. // Material
  32797. if (this.material) {
  32798. serializationObject.materialId = this.material.id;
  32799. }
  32800. else {
  32801. this.material = null;
  32802. }
  32803. // Morph targets
  32804. if (this.morphTargetManager) {
  32805. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32806. }
  32807. // Skeleton
  32808. if (this.skeleton) {
  32809. serializationObject.skeletonId = this.skeleton.id;
  32810. }
  32811. // Physics
  32812. //TODO implement correct serialization for physics impostors.
  32813. var impostor = this.getPhysicsImpostor();
  32814. if (impostor) {
  32815. serializationObject.physicsMass = impostor.getParam("mass");
  32816. serializationObject.physicsFriction = impostor.getParam("friction");
  32817. serializationObject.physicsRestitution = impostor.getParam("mass");
  32818. serializationObject.physicsImpostor = impostor.type;
  32819. }
  32820. // Metadata
  32821. if (this.metadata) {
  32822. serializationObject.metadata = this.metadata;
  32823. }
  32824. // Instances
  32825. serializationObject.instances = [];
  32826. for (var index = 0; index < this.instances.length; index++) {
  32827. var instance = this.instances[index];
  32828. var serializationInstance = {
  32829. name: instance.name,
  32830. id: instance.id,
  32831. position: instance.position.asArray(),
  32832. scaling: instance.scaling.asArray()
  32833. };
  32834. if (instance.rotationQuaternion) {
  32835. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32836. }
  32837. else if (instance.rotation) {
  32838. serializationInstance.rotation = instance.rotation.asArray();
  32839. }
  32840. serializationObject.instances.push(serializationInstance);
  32841. // Animations
  32842. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32843. serializationInstance.ranges = instance.serializeAnimationRanges();
  32844. }
  32845. //
  32846. // Animations
  32847. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32848. serializationObject.ranges = this.serializeAnimationRanges();
  32849. // Layer mask
  32850. serializationObject.layerMask = this.layerMask;
  32851. // Alpha
  32852. serializationObject.alphaIndex = this.alphaIndex;
  32853. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32854. // Overlay
  32855. serializationObject.overlayAlpha = this.overlayAlpha;
  32856. serializationObject.overlayColor = this.overlayColor.asArray();
  32857. serializationObject.renderOverlay = this.renderOverlay;
  32858. // Fog
  32859. serializationObject.applyFog = this.applyFog;
  32860. // Action Manager
  32861. if (this.actionManager) {
  32862. serializationObject.actions = this.actionManager.serialize(this.name);
  32863. }
  32864. };
  32865. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32866. if (!this.geometry) {
  32867. return;
  32868. }
  32869. this._markSubMeshesAsAttributesDirty();
  32870. var morphTargetManager = this._morphTargetManager;
  32871. if (morphTargetManager && morphTargetManager.vertexCount) {
  32872. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32873. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32874. this.morphTargetManager = null;
  32875. return;
  32876. }
  32877. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32878. var morphTarget = morphTargetManager.getActiveTarget(index);
  32879. var positions = morphTarget.getPositions();
  32880. if (!positions) {
  32881. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32882. return;
  32883. }
  32884. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32885. var normals = morphTarget.getNormals();
  32886. if (normals) {
  32887. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32888. }
  32889. var tangents = morphTarget.getTangents();
  32890. if (tangents) {
  32891. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32892. }
  32893. }
  32894. }
  32895. else {
  32896. var index = 0;
  32897. // Positions
  32898. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32899. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32900. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32901. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32902. }
  32903. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32904. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32905. }
  32906. index++;
  32907. }
  32908. }
  32909. };
  32910. // Statics
  32911. /**
  32912. * Returns a new Mesh object parsed from the source provided.
  32913. * The parameter `parsedMesh` is the source.
  32914. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32915. */
  32916. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32917. var mesh;
  32918. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32919. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32920. }
  32921. else {
  32922. mesh = new Mesh(parsedMesh.name, scene);
  32923. }
  32924. mesh.id = parsedMesh.id;
  32925. if (BABYLON.Tags) {
  32926. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32927. }
  32928. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32929. if (parsedMesh.metadata !== undefined) {
  32930. mesh.metadata = parsedMesh.metadata;
  32931. }
  32932. if (parsedMesh.rotationQuaternion) {
  32933. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32934. }
  32935. else if (parsedMesh.rotation) {
  32936. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32937. }
  32938. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32939. if (parsedMesh.localMatrix) {
  32940. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32941. }
  32942. else if (parsedMesh.pivotMatrix) {
  32943. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32944. }
  32945. mesh.setEnabled(parsedMesh.isEnabled);
  32946. mesh.isVisible = parsedMesh.isVisible;
  32947. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32948. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32949. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32950. if (parsedMesh.applyFog !== undefined) {
  32951. mesh.applyFog = parsedMesh.applyFog;
  32952. }
  32953. if (parsedMesh.pickable !== undefined) {
  32954. mesh.isPickable = parsedMesh.pickable;
  32955. }
  32956. if (parsedMesh.alphaIndex !== undefined) {
  32957. mesh.alphaIndex = parsedMesh.alphaIndex;
  32958. }
  32959. mesh.receiveShadows = parsedMesh.receiveShadows;
  32960. mesh.billboardMode = parsedMesh.billboardMode;
  32961. if (parsedMesh.visibility !== undefined) {
  32962. mesh.visibility = parsedMesh.visibility;
  32963. }
  32964. mesh.checkCollisions = parsedMesh.checkCollisions;
  32965. if (parsedMesh.isBlocker !== undefined) {
  32966. mesh.isBlocker = parsedMesh.isBlocker;
  32967. }
  32968. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32969. // freezeWorldMatrix
  32970. if (parsedMesh.freezeWorldMatrix) {
  32971. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32972. }
  32973. // Parent
  32974. if (parsedMesh.parentId) {
  32975. mesh._waitingParentId = parsedMesh.parentId;
  32976. }
  32977. // Actions
  32978. if (parsedMesh.actions !== undefined) {
  32979. mesh._waitingActions = parsedMesh.actions;
  32980. }
  32981. // Overlay
  32982. if (parsedMesh.overlayAlpha !== undefined) {
  32983. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32984. }
  32985. if (parsedMesh.overlayColor !== undefined) {
  32986. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32987. }
  32988. if (parsedMesh.renderOverlay !== undefined) {
  32989. mesh.renderOverlay = parsedMesh.renderOverlay;
  32990. }
  32991. // Geometry
  32992. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32993. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32994. if (parsedMesh.delayLoadingFile) {
  32995. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32996. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32997. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32998. if (parsedMesh._binaryInfo) {
  32999. mesh._binaryInfo = parsedMesh._binaryInfo;
  33000. }
  33001. mesh._delayInfo = [];
  33002. if (parsedMesh.hasUVs) {
  33003. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33004. }
  33005. if (parsedMesh.hasUVs2) {
  33006. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33007. }
  33008. if (parsedMesh.hasUVs3) {
  33009. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33010. }
  33011. if (parsedMesh.hasUVs4) {
  33012. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33013. }
  33014. if (parsedMesh.hasUVs5) {
  33015. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33016. }
  33017. if (parsedMesh.hasUVs6) {
  33018. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33019. }
  33020. if (parsedMesh.hasColors) {
  33021. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33022. }
  33023. if (parsedMesh.hasMatricesIndices) {
  33024. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33025. }
  33026. if (parsedMesh.hasMatricesWeights) {
  33027. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33028. }
  33029. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33030. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33031. mesh._checkDelayState();
  33032. }
  33033. }
  33034. else {
  33035. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33036. }
  33037. // Material
  33038. if (parsedMesh.materialId) {
  33039. mesh.setMaterialByID(parsedMesh.materialId);
  33040. }
  33041. else {
  33042. mesh.material = null;
  33043. }
  33044. // Morph targets
  33045. if (parsedMesh.morphTargetManagerId > -1) {
  33046. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33047. }
  33048. // Skeleton
  33049. if (parsedMesh.skeletonId > -1) {
  33050. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33051. if (parsedMesh.numBoneInfluencers) {
  33052. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33053. }
  33054. }
  33055. // Animations
  33056. if (parsedMesh.animations) {
  33057. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33058. var parsedAnimation = parsedMesh.animations[animationIndex];
  33059. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33060. }
  33061. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33062. }
  33063. if (parsedMesh.autoAnimate) {
  33064. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33065. }
  33066. // Layer Mask
  33067. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33068. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33069. }
  33070. else {
  33071. mesh.layerMask = 0x0FFFFFFF;
  33072. }
  33073. // Physics
  33074. if (parsedMesh.physicsImpostor) {
  33075. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33076. mass: parsedMesh.physicsMass,
  33077. friction: parsedMesh.physicsFriction,
  33078. restitution: parsedMesh.physicsRestitution
  33079. }, scene);
  33080. }
  33081. // Instances
  33082. if (parsedMesh.instances) {
  33083. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33084. var parsedInstance = parsedMesh.instances[index];
  33085. var instance = mesh.createInstance(parsedInstance.name);
  33086. if (parsedInstance.id) {
  33087. instance.id = parsedInstance.id;
  33088. }
  33089. if (BABYLON.Tags) {
  33090. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33091. }
  33092. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33093. if (parsedInstance.parentId) {
  33094. instance._waitingParentId = parsedInstance.parentId;
  33095. }
  33096. if (parsedInstance.rotationQuaternion) {
  33097. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33098. }
  33099. else if (parsedInstance.rotation) {
  33100. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33101. }
  33102. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33103. instance.checkCollisions = mesh.checkCollisions;
  33104. if (parsedMesh.animations) {
  33105. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33106. parsedAnimation = parsedMesh.animations[animationIndex];
  33107. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33108. }
  33109. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33110. }
  33111. }
  33112. }
  33113. return mesh;
  33114. };
  33115. /**
  33116. * Creates a ribbon mesh.
  33117. * Please consider using the same method from the MeshBuilder class instead.
  33118. * 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.
  33119. *
  33120. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33121. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33122. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33123. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33124. * 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.
  33125. * 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.
  33126. * 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
  33127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33128. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33130. */
  33131. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33132. if (closeArray === void 0) { closeArray = false; }
  33133. if (updatable === void 0) { updatable = false; }
  33134. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33135. pathArray: pathArray,
  33136. closeArray: closeArray,
  33137. closePath: closePath,
  33138. offset: offset,
  33139. updatable: updatable,
  33140. sideOrientation: sideOrientation,
  33141. instance: instance
  33142. }, scene);
  33143. };
  33144. /**
  33145. * Creates a plane polygonal mesh. By default, this is a disc.
  33146. * Please consider using the same method from the MeshBuilder class instead.
  33147. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33148. * 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.
  33149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33150. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33152. */
  33153. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33154. if (scene === void 0) { scene = null; }
  33155. var options = {
  33156. radius: radius,
  33157. tessellation: tessellation,
  33158. sideOrientation: sideOrientation,
  33159. updatable: updatable
  33160. };
  33161. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33162. };
  33163. /**
  33164. * Creates a box mesh.
  33165. * Please consider using the same method from the MeshBuilder class instead.
  33166. * The parameter `size` sets the size (float) of each box side (default 1).
  33167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33168. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33170. */
  33171. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33172. if (scene === void 0) { scene = null; }
  33173. var options = {
  33174. size: size,
  33175. sideOrientation: sideOrientation,
  33176. updatable: updatable
  33177. };
  33178. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33179. };
  33180. /**
  33181. * Creates a sphere mesh.
  33182. * Please consider using the same method from the MeshBuilder class instead.
  33183. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33184. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33186. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33188. */
  33189. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33190. var options = {
  33191. segments: segments,
  33192. diameterX: diameter,
  33193. diameterY: diameter,
  33194. diameterZ: diameter,
  33195. sideOrientation: sideOrientation,
  33196. updatable: updatable
  33197. };
  33198. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33199. };
  33200. /**
  33201. * Creates a cylinder or a cone mesh.
  33202. * Please consider using the same method from the MeshBuilder class instead.
  33203. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33204. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33205. * 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.
  33206. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33207. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33208. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33209. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33211. */
  33212. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33213. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33214. if (scene !== undefined) {
  33215. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33216. updatable = scene;
  33217. }
  33218. scene = subdivisions;
  33219. subdivisions = 1;
  33220. }
  33221. var options = {
  33222. height: height,
  33223. diameterTop: diameterTop,
  33224. diameterBottom: diameterBottom,
  33225. tessellation: tessellation,
  33226. subdivisions: subdivisions,
  33227. sideOrientation: sideOrientation,
  33228. updatable: updatable
  33229. };
  33230. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33231. };
  33232. // Torus (Code from SharpDX.org)
  33233. /**
  33234. * Creates a torus mesh.
  33235. * Please consider using the same method from the MeshBuilder class instead.
  33236. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33237. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33238. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33239. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33240. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33242. */
  33243. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33244. var options = {
  33245. diameter: diameter,
  33246. thickness: thickness,
  33247. tessellation: tessellation,
  33248. sideOrientation: sideOrientation,
  33249. updatable: updatable
  33250. };
  33251. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33252. };
  33253. /**
  33254. * Creates a torus knot mesh.
  33255. * Please consider using the same method from the MeshBuilder class instead.
  33256. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33257. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33258. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33259. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33261. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33263. */
  33264. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33265. var options = {
  33266. radius: radius,
  33267. tube: tube,
  33268. radialSegments: radialSegments,
  33269. tubularSegments: tubularSegments,
  33270. p: p,
  33271. q: q,
  33272. sideOrientation: sideOrientation,
  33273. updatable: updatable
  33274. };
  33275. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33276. };
  33277. /**
  33278. * Creates a line mesh.
  33279. * Please consider using the same method from the MeshBuilder class instead.
  33280. * 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.
  33281. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33282. * The parameter `points` is an array successive Vector3.
  33283. * 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
  33284. * When updating an instance, remember that only point positions can change, not the number of points.
  33285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33286. */
  33287. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33288. if (scene === void 0) { scene = null; }
  33289. if (updatable === void 0) { updatable = false; }
  33290. if (instance === void 0) { instance = null; }
  33291. var options = {
  33292. points: points,
  33293. updatable: updatable,
  33294. instance: instance
  33295. };
  33296. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33297. };
  33298. /**
  33299. * Creates a dashed line mesh.
  33300. * Please consider using the same method from the MeshBuilder class instead.
  33301. * 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.
  33302. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33303. * The parameter `points` is an array successive Vector3.
  33304. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33305. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33306. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33307. * 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
  33308. * When updating an instance, remember that only point positions can change, not the number of points.
  33309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33310. */
  33311. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33312. if (scene === void 0) { scene = null; }
  33313. var options = {
  33314. points: points,
  33315. dashSize: dashSize,
  33316. gapSize: gapSize,
  33317. dashNb: dashNb,
  33318. updatable: updatable,
  33319. instance: instance
  33320. };
  33321. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33322. };
  33323. /**
  33324. * Creates a polygon mesh.
  33325. * Please consider using the same method from the MeshBuilder class instead.
  33326. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33327. * 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.
  33328. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33330. * Remember you can only change the shape positions, not their number when updating a polygon.
  33331. */
  33332. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33333. var options = {
  33334. shape: shape,
  33335. holes: holes,
  33336. updatable: updatable,
  33337. sideOrientation: sideOrientation
  33338. };
  33339. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33340. };
  33341. /**
  33342. * Creates an extruded polygon mesh, with depth in the Y direction.
  33343. * Please consider using the same method from the MeshBuilder class instead.
  33344. */
  33345. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33346. var options = {
  33347. shape: shape,
  33348. holes: holes,
  33349. depth: depth,
  33350. updatable: updatable,
  33351. sideOrientation: sideOrientation
  33352. };
  33353. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33354. };
  33355. /**
  33356. * Creates an extruded shape mesh.
  33357. * 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.
  33358. * Please consider using the same method from the MeshBuilder class instead.
  33359. *
  33360. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33361. * 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
  33362. * extruded along the Z axis.
  33363. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33364. * 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.
  33365. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33366. * 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
  33367. * 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
  33368. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33370. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33372. */
  33373. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33374. if (scene === void 0) { scene = null; }
  33375. var options = {
  33376. shape: shape,
  33377. path: path,
  33378. scale: scale,
  33379. rotation: rotation,
  33380. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33381. sideOrientation: sideOrientation,
  33382. instance: instance,
  33383. updatable: updatable
  33384. };
  33385. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33386. };
  33387. /**
  33388. * Creates an custom extruded shape mesh.
  33389. * 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.
  33390. * Please consider using the same method from the MeshBuilder class instead.
  33391. *
  33392. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33393. * 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
  33394. * extruded along the Z axis.
  33395. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33396. * 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
  33397. * and the distance of this point from the begining of the path :
  33398. * ```javascript
  33399. * var rotationFunction = function(i, distance) {
  33400. * // do things
  33401. * return rotationValue; }
  33402. * ```
  33403. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33404. * 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
  33405. * and the distance of this point from the begining of the path :
  33406. * ```javascript
  33407. * var scaleFunction = function(i, distance) {
  33408. * // do things
  33409. * return scaleValue;}
  33410. * ```
  33411. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33412. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33413. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33414. * 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
  33415. * 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
  33416. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33418. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33420. */
  33421. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33422. var options = {
  33423. shape: shape,
  33424. path: path,
  33425. scaleFunction: scaleFunction,
  33426. rotationFunction: rotationFunction,
  33427. ribbonCloseArray: ribbonCloseArray,
  33428. ribbonClosePath: ribbonClosePath,
  33429. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33430. sideOrientation: sideOrientation,
  33431. instance: instance,
  33432. updatable: updatable
  33433. };
  33434. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33435. };
  33436. /**
  33437. * Creates lathe mesh.
  33438. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33439. * Please consider using the same method from the MeshBuilder class instead.
  33440. * 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
  33441. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33442. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33443. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33445. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33447. */
  33448. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33449. var options = {
  33450. shape: shape,
  33451. radius: radius,
  33452. tessellation: tessellation,
  33453. sideOrientation: sideOrientation,
  33454. updatable: updatable
  33455. };
  33456. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33457. };
  33458. /**
  33459. * Creates a plane mesh.
  33460. * Please consider using the same method from the MeshBuilder class instead.
  33461. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33462. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33463. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33464. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33465. */
  33466. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33467. var options = {
  33468. size: size,
  33469. width: size,
  33470. height: size,
  33471. sideOrientation: sideOrientation,
  33472. updatable: updatable
  33473. };
  33474. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33475. };
  33476. /**
  33477. * Creates a ground mesh.
  33478. * Please consider using the same method from the MeshBuilder class instead.
  33479. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33480. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33482. */
  33483. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33484. var options = {
  33485. width: width,
  33486. height: height,
  33487. subdivisions: subdivisions,
  33488. updatable: updatable
  33489. };
  33490. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33491. };
  33492. /**
  33493. * Creates a tiled ground mesh.
  33494. * Please consider using the same method from the MeshBuilder class instead.
  33495. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33496. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33497. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33498. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33499. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33500. * numbers of subdivisions on the ground width and height of each tile.
  33501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33502. */
  33503. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33504. var options = {
  33505. xmin: xmin,
  33506. zmin: zmin,
  33507. xmax: xmax,
  33508. zmax: zmax,
  33509. subdivisions: subdivisions,
  33510. precision: precision,
  33511. updatable: updatable
  33512. };
  33513. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33514. };
  33515. /**
  33516. * Creates a ground mesh from a height map.
  33517. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33518. * Please consider using the same method from the MeshBuilder class instead.
  33519. * The parameter `url` sets the URL of the height map image resource.
  33520. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33521. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33522. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33523. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33524. * 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).
  33525. * This function is passed the newly built mesh :
  33526. * ```javascript
  33527. * function(mesh) { // do things
  33528. * return; }
  33529. * ```
  33530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33531. */
  33532. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33533. var options = {
  33534. width: width,
  33535. height: height,
  33536. subdivisions: subdivisions,
  33537. minHeight: minHeight,
  33538. maxHeight: maxHeight,
  33539. updatable: updatable,
  33540. onReady: onReady
  33541. };
  33542. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33543. };
  33544. /**
  33545. * Creates a tube mesh.
  33546. * 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.
  33547. * Please consider using the same method from the MeshBuilder class instead.
  33548. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33549. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33550. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33551. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33552. * 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.
  33553. * It must return a radius value (positive float) :
  33554. * ```javascript
  33555. * var radiusFunction = function(i, distance) {
  33556. * // do things
  33557. * return radius; }
  33558. * ```
  33559. * 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
  33560. * 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
  33561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33562. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33564. */
  33565. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33566. var options = {
  33567. path: path,
  33568. radius: radius,
  33569. tessellation: tessellation,
  33570. radiusFunction: radiusFunction,
  33571. arc: 1,
  33572. cap: cap,
  33573. updatable: updatable,
  33574. sideOrientation: sideOrientation,
  33575. instance: instance
  33576. };
  33577. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33578. };
  33579. /**
  33580. * Creates a polyhedron mesh.
  33581. * Please consider using the same method from the MeshBuilder class instead.
  33582. * 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
  33583. * to choose the wanted type.
  33584. * The parameter `size` (positive float, default 1) sets the polygon size.
  33585. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33586. * 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`.
  33587. * 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
  33588. * 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)`).
  33589. * 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
  33590. * 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.
  33591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33592. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33594. */
  33595. Mesh.CreatePolyhedron = function (name, options, scene) {
  33596. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33597. };
  33598. /**
  33599. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33600. * Please consider using the same method from the MeshBuilder class instead.
  33601. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33602. * 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`).
  33603. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33604. * 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.
  33605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33606. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33608. */
  33609. Mesh.CreateIcoSphere = function (name, options, scene) {
  33610. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33611. };
  33612. /**
  33613. * Creates a decal mesh.
  33614. * Please consider using the same method from the MeshBuilder class instead.
  33615. * 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.
  33616. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33617. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33618. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33619. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33620. */
  33621. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33622. var options = {
  33623. position: position,
  33624. normal: normal,
  33625. size: size,
  33626. angle: angle
  33627. };
  33628. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33629. };
  33630. // Skeletons
  33631. /**
  33632. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33633. */
  33634. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33635. if (!this._sourcePositions) {
  33636. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33637. if (!source) {
  33638. return this._sourcePositions;
  33639. }
  33640. this._sourcePositions = new Float32Array(source);
  33641. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33642. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33643. }
  33644. }
  33645. return this._sourcePositions;
  33646. };
  33647. /**
  33648. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33649. */
  33650. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33651. if (!this._sourceNormals) {
  33652. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33653. if (!source) {
  33654. return this._sourceNormals;
  33655. }
  33656. this._sourceNormals = new Float32Array(source);
  33657. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33658. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33659. }
  33660. }
  33661. return this._sourceNormals;
  33662. };
  33663. /**
  33664. * Updates the vertex buffer by applying transformation from the bones.
  33665. * Returns the Mesh.
  33666. *
  33667. * @param {skeleton} skeleton to apply
  33668. */
  33669. Mesh.prototype.applySkeleton = function (skeleton) {
  33670. if (!this.geometry) {
  33671. return this;
  33672. }
  33673. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33674. return this;
  33675. }
  33676. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33677. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33678. return this;
  33679. }
  33680. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33681. return this;
  33682. }
  33683. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33684. return this;
  33685. }
  33686. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33687. return this;
  33688. }
  33689. if (!this._sourcePositions) {
  33690. var submeshes = this.subMeshes.slice();
  33691. this.setPositionsForCPUSkinning();
  33692. this.subMeshes = submeshes;
  33693. }
  33694. if (!this._sourceNormals) {
  33695. this.setNormalsForCPUSkinning();
  33696. }
  33697. // positionsData checks for not being Float32Array will only pass at most once
  33698. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33699. if (!positionsData) {
  33700. return this;
  33701. }
  33702. if (!(positionsData instanceof Float32Array)) {
  33703. positionsData = new Float32Array(positionsData);
  33704. }
  33705. // normalsData checks for not being Float32Array will only pass at most once
  33706. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33707. if (!normalsData) {
  33708. return this;
  33709. }
  33710. if (!(normalsData instanceof Float32Array)) {
  33711. normalsData = new Float32Array(normalsData);
  33712. }
  33713. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33714. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33715. if (!matricesWeightsData || !matricesIndicesData) {
  33716. return this;
  33717. }
  33718. var needExtras = this.numBoneInfluencers > 4;
  33719. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33720. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33721. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33722. var tempVector3 = BABYLON.Vector3.Zero();
  33723. var finalMatrix = new BABYLON.Matrix();
  33724. var tempMatrix = new BABYLON.Matrix();
  33725. var matWeightIdx = 0;
  33726. var inf;
  33727. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33728. var weight;
  33729. for (inf = 0; inf < 4; inf++) {
  33730. weight = matricesWeightsData[matWeightIdx + inf];
  33731. if (weight > 0) {
  33732. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33733. finalMatrix.addToSelf(tempMatrix);
  33734. }
  33735. else
  33736. break;
  33737. }
  33738. if (needExtras) {
  33739. for (inf = 0; inf < 4; inf++) {
  33740. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33741. if (weight > 0) {
  33742. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33743. finalMatrix.addToSelf(tempMatrix);
  33744. }
  33745. else
  33746. break;
  33747. }
  33748. }
  33749. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33750. tempVector3.toArray(positionsData, index);
  33751. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33752. tempVector3.toArray(normalsData, index);
  33753. finalMatrix.reset();
  33754. }
  33755. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33756. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33757. return this;
  33758. };
  33759. // Tools
  33760. /**
  33761. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33762. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33763. */
  33764. Mesh.MinMax = function (meshes) {
  33765. var minVector = null;
  33766. var maxVector = null;
  33767. meshes.forEach(function (mesh, index, array) {
  33768. var boundingInfo = mesh.getBoundingInfo();
  33769. var boundingBox = boundingInfo.boundingBox;
  33770. if (!minVector || !maxVector) {
  33771. minVector = boundingBox.minimumWorld;
  33772. maxVector = boundingBox.maximumWorld;
  33773. }
  33774. else {
  33775. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33776. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33777. }
  33778. });
  33779. if (!minVector || !maxVector) {
  33780. return {
  33781. min: BABYLON.Vector3.Zero(),
  33782. max: BABYLON.Vector3.Zero()
  33783. };
  33784. }
  33785. return {
  33786. min: minVector,
  33787. max: maxVector
  33788. };
  33789. };
  33790. /**
  33791. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33792. */
  33793. Mesh.Center = function (meshesOrMinMaxVector) {
  33794. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33795. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33796. };
  33797. /**
  33798. * Merge the array of meshes into a single mesh for performance reasons.
  33799. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33800. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33801. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33802. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33803. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33804. */
  33805. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33806. if (disposeSource === void 0) { disposeSource = true; }
  33807. var index;
  33808. if (!allow32BitsIndices) {
  33809. var totalVertices = 0;
  33810. // Counting vertices
  33811. for (index = 0; index < meshes.length; index++) {
  33812. if (meshes[index]) {
  33813. totalVertices += meshes[index].getTotalVertices();
  33814. if (totalVertices > 65536) {
  33815. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33816. return null;
  33817. }
  33818. }
  33819. }
  33820. }
  33821. // Merge
  33822. var vertexData = null;
  33823. var otherVertexData;
  33824. var indiceArray = new Array();
  33825. var source = null;
  33826. for (index = 0; index < meshes.length; index++) {
  33827. if (meshes[index]) {
  33828. meshes[index].computeWorldMatrix(true);
  33829. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33830. otherVertexData.transform(meshes[index].getWorldMatrix());
  33831. if (vertexData) {
  33832. vertexData.merge(otherVertexData);
  33833. }
  33834. else {
  33835. vertexData = otherVertexData;
  33836. source = meshes[index];
  33837. }
  33838. if (subdivideWithSubMeshes) {
  33839. indiceArray.push(meshes[index].getTotalIndices());
  33840. }
  33841. }
  33842. }
  33843. source = source;
  33844. if (!meshSubclass) {
  33845. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33846. }
  33847. vertexData.applyToMesh(meshSubclass);
  33848. // Setting properties
  33849. meshSubclass.material = source.material;
  33850. meshSubclass.checkCollisions = source.checkCollisions;
  33851. // Cleaning
  33852. if (disposeSource) {
  33853. for (index = 0; index < meshes.length; index++) {
  33854. if (meshes[index]) {
  33855. meshes[index].dispose();
  33856. }
  33857. }
  33858. }
  33859. // Subdivide
  33860. if (subdivideWithSubMeshes) {
  33861. //-- Suppresions du submesh global
  33862. meshSubclass.releaseSubMeshes();
  33863. index = 0;
  33864. var offset = 0;
  33865. //-- aplique la subdivision en fonction du tableau d'indices
  33866. while (index < indiceArray.length) {
  33867. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33868. offset += indiceArray[index];
  33869. index++;
  33870. }
  33871. }
  33872. return meshSubclass;
  33873. };
  33874. // Consts
  33875. Mesh._FRONTSIDE = 0;
  33876. Mesh._BACKSIDE = 1;
  33877. Mesh._DOUBLESIDE = 2;
  33878. Mesh._DEFAULTSIDE = 0;
  33879. Mesh._NO_CAP = 0;
  33880. Mesh._CAP_START = 1;
  33881. Mesh._CAP_END = 2;
  33882. Mesh._CAP_ALL = 3;
  33883. return Mesh;
  33884. }(BABYLON.AbstractMesh));
  33885. BABYLON.Mesh = Mesh;
  33886. })(BABYLON || (BABYLON = {}));
  33887. //# sourceMappingURL=babylon.mesh.js.map
  33888. var BABYLON;
  33889. (function (BABYLON) {
  33890. var BaseSubMesh = /** @class */ (function () {
  33891. function BaseSubMesh() {
  33892. }
  33893. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33894. get: function () {
  33895. return this._materialEffect;
  33896. },
  33897. enumerable: true,
  33898. configurable: true
  33899. });
  33900. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33901. if (defines === void 0) { defines = null; }
  33902. if (this._materialEffect === effect) {
  33903. if (!effect) {
  33904. this._materialDefines = null;
  33905. }
  33906. return;
  33907. }
  33908. this._materialDefines = defines;
  33909. this._materialEffect = effect;
  33910. };
  33911. return BaseSubMesh;
  33912. }());
  33913. BABYLON.BaseSubMesh = BaseSubMesh;
  33914. var SubMesh = /** @class */ (function (_super) {
  33915. __extends(SubMesh, _super);
  33916. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33917. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33918. var _this = _super.call(this) || this;
  33919. _this.materialIndex = materialIndex;
  33920. _this.verticesStart = verticesStart;
  33921. _this.verticesCount = verticesCount;
  33922. _this.indexStart = indexStart;
  33923. _this.indexCount = indexCount;
  33924. _this._renderId = 0;
  33925. _this._mesh = mesh;
  33926. _this._renderingMesh = renderingMesh || mesh;
  33927. mesh.subMeshes.push(_this);
  33928. _this._trianglePlanes = [];
  33929. _this._id = mesh.subMeshes.length - 1;
  33930. if (createBoundingBox) {
  33931. _this.refreshBoundingInfo();
  33932. mesh.computeWorldMatrix(true);
  33933. }
  33934. return _this;
  33935. }
  33936. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33937. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33938. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33939. };
  33940. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33941. get: function () {
  33942. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33943. },
  33944. enumerable: true,
  33945. configurable: true
  33946. });
  33947. /**
  33948. * Returns the submesh BoudingInfo object.
  33949. */
  33950. SubMesh.prototype.getBoundingInfo = function () {
  33951. if (this.IsGlobal) {
  33952. return this._mesh.getBoundingInfo();
  33953. }
  33954. return this._boundingInfo;
  33955. };
  33956. /**
  33957. * Sets the submesh BoundingInfo.
  33958. * Return the SubMesh.
  33959. */
  33960. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33961. this._boundingInfo = boundingInfo;
  33962. return this;
  33963. };
  33964. /**
  33965. * Returns the mesh of the current submesh.
  33966. */
  33967. SubMesh.prototype.getMesh = function () {
  33968. return this._mesh;
  33969. };
  33970. /**
  33971. * Returns the rendering mesh of the submesh.
  33972. */
  33973. SubMesh.prototype.getRenderingMesh = function () {
  33974. return this._renderingMesh;
  33975. };
  33976. /**
  33977. * Returns the submesh material.
  33978. */
  33979. SubMesh.prototype.getMaterial = function () {
  33980. var rootMaterial = this._renderingMesh.material;
  33981. if (rootMaterial === null || rootMaterial === undefined) {
  33982. return this._mesh.getScene().defaultMaterial;
  33983. }
  33984. else if (rootMaterial.getSubMaterial) {
  33985. var multiMaterial = rootMaterial;
  33986. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33987. if (this._currentMaterial !== effectiveMaterial) {
  33988. this._currentMaterial = effectiveMaterial;
  33989. this._materialDefines = null;
  33990. }
  33991. return effectiveMaterial;
  33992. }
  33993. return rootMaterial;
  33994. };
  33995. // Methods
  33996. /**
  33997. * Sets a new updated BoundingInfo object to the submesh.
  33998. * Returns the SubMesh.
  33999. */
  34000. SubMesh.prototype.refreshBoundingInfo = function () {
  34001. this._lastColliderWorldVertices = null;
  34002. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34003. return this;
  34004. }
  34005. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34006. if (!data) {
  34007. this._boundingInfo = this._mesh.getBoundingInfo();
  34008. return this;
  34009. }
  34010. var indices = this._renderingMesh.getIndices();
  34011. var extend;
  34012. //is this the only submesh?
  34013. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34014. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34015. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34016. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34017. }
  34018. else {
  34019. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34020. }
  34021. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34022. return this;
  34023. };
  34024. SubMesh.prototype._checkCollision = function (collider) {
  34025. var boundingInfo = this.getBoundingInfo();
  34026. return boundingInfo._checkCollision(collider);
  34027. };
  34028. /**
  34029. * Updates the submesh BoundingInfo.
  34030. * Returns the Submesh.
  34031. */
  34032. SubMesh.prototype.updateBoundingInfo = function (world) {
  34033. var boundingInfo = this.getBoundingInfo();
  34034. if (!boundingInfo) {
  34035. this.refreshBoundingInfo();
  34036. boundingInfo = this.getBoundingInfo();
  34037. }
  34038. boundingInfo.update(world);
  34039. return this;
  34040. };
  34041. /**
  34042. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34043. * Boolean returned.
  34044. */
  34045. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34046. var boundingInfo = this.getBoundingInfo();
  34047. if (!boundingInfo) {
  34048. return false;
  34049. }
  34050. return boundingInfo.isInFrustum(frustumPlanes);
  34051. };
  34052. /**
  34053. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34054. * Boolean returned.
  34055. */
  34056. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34057. var boundingInfo = this.getBoundingInfo();
  34058. if (!boundingInfo) {
  34059. return false;
  34060. }
  34061. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34062. };
  34063. /**
  34064. * Renders the submesh.
  34065. * Returns it.
  34066. */
  34067. SubMesh.prototype.render = function (enableAlphaMode) {
  34068. this._renderingMesh.render(this, enableAlphaMode);
  34069. return this;
  34070. };
  34071. /**
  34072. * Returns a new Index Buffer.
  34073. * Type returned : WebGLBuffer.
  34074. */
  34075. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34076. if (!this._linesIndexBuffer) {
  34077. var linesIndices = [];
  34078. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34079. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34080. }
  34081. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34082. this.linesIndexCount = linesIndices.length;
  34083. }
  34084. return this._linesIndexBuffer;
  34085. };
  34086. /**
  34087. * True is the passed Ray intersects the submesh bounding box.
  34088. * Boolean returned.
  34089. */
  34090. SubMesh.prototype.canIntersects = function (ray) {
  34091. var boundingInfo = this.getBoundingInfo();
  34092. if (!boundingInfo) {
  34093. return false;
  34094. }
  34095. return ray.intersectsBox(boundingInfo.boundingBox);
  34096. };
  34097. /**
  34098. * Returns an object IntersectionInfo.
  34099. */
  34100. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34101. var intersectInfo = null;
  34102. var material = this.getMaterial();
  34103. if (!material) {
  34104. return null;
  34105. }
  34106. switch (material.fillMode) {
  34107. case BABYLON.Material.PointListDrawMode:
  34108. case BABYLON.Material.LineListDrawMode:
  34109. case BABYLON.Material.LineLoopDrawMode:
  34110. case BABYLON.Material.LineStripDrawMode:
  34111. case BABYLON.Material.TriangleFanDrawMode:
  34112. case BABYLON.Material.TriangleStripDrawMode:
  34113. return null;
  34114. }
  34115. // LineMesh first as it's also a Mesh...
  34116. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34117. var lineMesh = this._mesh;
  34118. // Line test
  34119. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34120. var p0 = positions[indices[index]];
  34121. var p1 = positions[indices[index + 1]];
  34122. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34123. if (length < 0) {
  34124. continue;
  34125. }
  34126. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34127. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34128. if (fastCheck) {
  34129. break;
  34130. }
  34131. }
  34132. }
  34133. }
  34134. else {
  34135. // Triangles test
  34136. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34137. var p0 = positions[indices[index]];
  34138. var p1 = positions[indices[index + 1]];
  34139. var p2 = positions[indices[index + 2]];
  34140. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34141. if (currentIntersectInfo) {
  34142. if (currentIntersectInfo.distance < 0) {
  34143. continue;
  34144. }
  34145. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34146. intersectInfo = currentIntersectInfo;
  34147. intersectInfo.faceId = index / 3;
  34148. if (fastCheck) {
  34149. break;
  34150. }
  34151. }
  34152. }
  34153. }
  34154. }
  34155. return intersectInfo;
  34156. };
  34157. SubMesh.prototype._rebuild = function () {
  34158. if (this._linesIndexBuffer) {
  34159. this._linesIndexBuffer = null;
  34160. }
  34161. };
  34162. // Clone
  34163. /**
  34164. * Creates a new Submesh from the passed Mesh.
  34165. */
  34166. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34167. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34168. if (!this.IsGlobal) {
  34169. var boundingInfo = this.getBoundingInfo();
  34170. if (!boundingInfo) {
  34171. return result;
  34172. }
  34173. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34174. }
  34175. return result;
  34176. };
  34177. // Dispose
  34178. /**
  34179. * Disposes the Submesh.
  34180. * Returns nothing.
  34181. */
  34182. SubMesh.prototype.dispose = function () {
  34183. if (this._linesIndexBuffer) {
  34184. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34185. this._linesIndexBuffer = null;
  34186. }
  34187. // Remove from mesh
  34188. var index = this._mesh.subMeshes.indexOf(this);
  34189. this._mesh.subMeshes.splice(index, 1);
  34190. };
  34191. // Statics
  34192. /**
  34193. * Creates a new Submesh from the passed parameters :
  34194. * - materialIndex (integer) : the index of the main mesh material.
  34195. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34196. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34197. * - mesh (Mesh) : the main mesh to create the submesh from.
  34198. * - renderingMesh (optional Mesh) : rendering mesh.
  34199. */
  34200. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34201. var minVertexIndex = Number.MAX_VALUE;
  34202. var maxVertexIndex = -Number.MAX_VALUE;
  34203. renderingMesh = (renderingMesh || mesh);
  34204. var indices = renderingMesh.getIndices();
  34205. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34206. var vertexIndex = indices[index];
  34207. if (vertexIndex < minVertexIndex)
  34208. minVertexIndex = vertexIndex;
  34209. if (vertexIndex > maxVertexIndex)
  34210. maxVertexIndex = vertexIndex;
  34211. }
  34212. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34213. };
  34214. return SubMesh;
  34215. }(BaseSubMesh));
  34216. BABYLON.SubMesh = SubMesh;
  34217. })(BABYLON || (BABYLON = {}));
  34218. //# sourceMappingURL=babylon.subMesh.js.map
  34219. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34220. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34221. s = arguments[i];
  34222. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34223. t[p] = s[p];
  34224. }
  34225. return t;
  34226. };
  34227. var BABYLON;
  34228. (function (BABYLON) {
  34229. /**
  34230. * Manages the defines for the Material
  34231. */
  34232. var MaterialDefines = /** @class */ (function () {
  34233. function MaterialDefines() {
  34234. this._isDirty = true;
  34235. /** @hidden */
  34236. this._areLightsDirty = true;
  34237. /** @hidden */
  34238. this._areAttributesDirty = true;
  34239. /** @hidden */
  34240. this._areTexturesDirty = true;
  34241. /** @hidden */
  34242. this._areFresnelDirty = true;
  34243. /** @hidden */
  34244. this._areMiscDirty = true;
  34245. /** @hidden */
  34246. this._areImageProcessingDirty = true;
  34247. /** @hidden */
  34248. this._normals = false;
  34249. /** @hidden */
  34250. this._uvs = false;
  34251. /** @hidden */
  34252. this._needNormals = false;
  34253. /** @hidden */
  34254. this._needUVs = false;
  34255. }
  34256. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34257. /**
  34258. * Specifies if the material needs to be re-calculated
  34259. */
  34260. get: function () {
  34261. return this._isDirty;
  34262. },
  34263. enumerable: true,
  34264. configurable: true
  34265. });
  34266. /**
  34267. * Marks the material to indicate that it has been re-calculated
  34268. */
  34269. MaterialDefines.prototype.markAsProcessed = function () {
  34270. this._isDirty = false;
  34271. this._areAttributesDirty = false;
  34272. this._areTexturesDirty = false;
  34273. this._areFresnelDirty = false;
  34274. this._areLightsDirty = false;
  34275. this._areMiscDirty = false;
  34276. this._areImageProcessingDirty = false;
  34277. };
  34278. /**
  34279. * Marks the material to indicate that it needs to be re-calculated
  34280. */
  34281. MaterialDefines.prototype.markAsUnprocessed = function () {
  34282. this._isDirty = true;
  34283. };
  34284. /**
  34285. * Marks the material to indicate all of its defines need to be re-calculated
  34286. */
  34287. MaterialDefines.prototype.markAllAsDirty = function () {
  34288. this._areTexturesDirty = true;
  34289. this._areAttributesDirty = true;
  34290. this._areLightsDirty = true;
  34291. this._areFresnelDirty = true;
  34292. this._areMiscDirty = true;
  34293. this._areImageProcessingDirty = true;
  34294. this._isDirty = true;
  34295. };
  34296. /**
  34297. * Marks the material to indicate that image processing needs to be re-calculated
  34298. */
  34299. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34300. this._areImageProcessingDirty = true;
  34301. this._isDirty = true;
  34302. };
  34303. /**
  34304. * Marks the material to indicate the lights need to be re-calculated
  34305. */
  34306. MaterialDefines.prototype.markAsLightDirty = function () {
  34307. this._areLightsDirty = true;
  34308. this._isDirty = true;
  34309. };
  34310. /**
  34311. * Marks the attribute state as changed
  34312. */
  34313. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34314. this._areAttributesDirty = true;
  34315. this._isDirty = true;
  34316. };
  34317. /**
  34318. * Marks the texture state as changed
  34319. */
  34320. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34321. this._areTexturesDirty = true;
  34322. this._isDirty = true;
  34323. };
  34324. /**
  34325. * Marks the fresnel state as changed
  34326. */
  34327. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34328. this._areFresnelDirty = true;
  34329. this._isDirty = true;
  34330. };
  34331. /**
  34332. * Marks the misc state as changed
  34333. */
  34334. MaterialDefines.prototype.markAsMiscDirty = function () {
  34335. this._areMiscDirty = true;
  34336. this._isDirty = true;
  34337. };
  34338. /**
  34339. * Rebuilds the material defines
  34340. */
  34341. MaterialDefines.prototype.rebuild = function () {
  34342. if (this._keys) {
  34343. delete this._keys;
  34344. }
  34345. this._keys = [];
  34346. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34347. var key = _a[_i];
  34348. if (key[0] === "_") {
  34349. continue;
  34350. }
  34351. this._keys.push(key);
  34352. }
  34353. };
  34354. /**
  34355. * Specifies if two material defines are equal
  34356. * @param other - A material define instance to compare to
  34357. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34358. */
  34359. MaterialDefines.prototype.isEqual = function (other) {
  34360. if (this._keys.length !== other._keys.length) {
  34361. return false;
  34362. }
  34363. for (var index = 0; index < this._keys.length; index++) {
  34364. var prop = this._keys[index];
  34365. if (this[prop] !== other[prop]) {
  34366. return false;
  34367. }
  34368. }
  34369. return true;
  34370. };
  34371. /**
  34372. * Clones this instance's defines to another instance
  34373. * @param other - material defines to clone values to
  34374. */
  34375. MaterialDefines.prototype.cloneTo = function (other) {
  34376. if (this._keys.length !== other._keys.length) {
  34377. other._keys = this._keys.slice(0);
  34378. }
  34379. for (var index = 0; index < this._keys.length; index++) {
  34380. var prop = this._keys[index];
  34381. other[prop] = this[prop];
  34382. }
  34383. };
  34384. /**
  34385. * Resets the material define values
  34386. */
  34387. MaterialDefines.prototype.reset = function () {
  34388. for (var index = 0; index < this._keys.length; index++) {
  34389. var prop = this._keys[index];
  34390. var type = typeof this[prop];
  34391. switch (type) {
  34392. case "number":
  34393. this[prop] = 0;
  34394. break;
  34395. case "string":
  34396. this[prop] = "";
  34397. break;
  34398. default:
  34399. this[prop] = false;
  34400. break;
  34401. }
  34402. }
  34403. };
  34404. /**
  34405. * Converts the material define values to a string
  34406. * @returns - String of material define information
  34407. */
  34408. MaterialDefines.prototype.toString = function () {
  34409. var result = "";
  34410. for (var index = 0; index < this._keys.length; index++) {
  34411. var prop = this._keys[index];
  34412. var value = this[prop];
  34413. var type = typeof value;
  34414. switch (type) {
  34415. case "number":
  34416. case "string":
  34417. result += "#define " + prop + " " + value + "\n";
  34418. break;
  34419. default:
  34420. if (value) {
  34421. result += "#define " + prop + "\n";
  34422. }
  34423. break;
  34424. }
  34425. }
  34426. return result;
  34427. };
  34428. return MaterialDefines;
  34429. }());
  34430. BABYLON.MaterialDefines = MaterialDefines;
  34431. /**
  34432. * Base class for the main features of a material in Babylon.js
  34433. */
  34434. var Material = /** @class */ (function () {
  34435. /**
  34436. * Creates a material instance
  34437. * @param name defines the name of the material
  34438. * @param scene defines the scene to reference
  34439. * @param doNotAdd specifies if the material should be added to the scene
  34440. */
  34441. function Material(name, scene, doNotAdd) {
  34442. /**
  34443. * Specifies if the ready state should be checked on each call
  34444. */
  34445. this.checkReadyOnEveryCall = false;
  34446. /**
  34447. * Specifies if the ready state should be checked once
  34448. */
  34449. this.checkReadyOnlyOnce = false;
  34450. /**
  34451. * The state of the material
  34452. */
  34453. this.state = "";
  34454. /**
  34455. * The alpha value of the material
  34456. */
  34457. this._alpha = 1.0;
  34458. /**
  34459. * Specifies if back face culling is enabled
  34460. */
  34461. this._backFaceCulling = true;
  34462. /**
  34463. * Specifies if the material should be serialized
  34464. */
  34465. this.doNotSerialize = false;
  34466. /**
  34467. * Specifies if the effect should be stored on sub meshes
  34468. */
  34469. this.storeEffectOnSubMeshes = false;
  34470. /**
  34471. * An event triggered when the material is disposed
  34472. */
  34473. this.onDisposeObservable = new BABYLON.Observable();
  34474. /**
  34475. * An event triggered when the material is bound
  34476. */
  34477. this.onBindObservable = new BABYLON.Observable();
  34478. /**
  34479. * An event triggered when the material is unbound
  34480. */
  34481. this.onUnBindObservable = new BABYLON.Observable();
  34482. /**
  34483. * Stores the value of the alpha mode
  34484. */
  34485. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34486. /**
  34487. * Stores the state of the need depth pre-pass value
  34488. */
  34489. this._needDepthPrePass = false;
  34490. /**
  34491. * Specifies if depth writing should be disabled
  34492. */
  34493. this.disableDepthWrite = false;
  34494. /**
  34495. * Specifies if depth writing should be forced
  34496. */
  34497. this.forceDepthWrite = false;
  34498. /**
  34499. * Specifies if there should be a separate pass for culling
  34500. */
  34501. this.separateCullingPass = false;
  34502. /**
  34503. * Stores the state specifing if fog should be enabled
  34504. */
  34505. this._fogEnabled = true;
  34506. /**
  34507. * Stores the size of points
  34508. */
  34509. this.pointSize = 1.0;
  34510. /**
  34511. * Stores the z offset value
  34512. */
  34513. this.zOffset = 0;
  34514. /**
  34515. * Specifies if the material was previously ready
  34516. */
  34517. this._wasPreviouslyReady = false;
  34518. /**
  34519. * Stores the fill mode state
  34520. */
  34521. this._fillMode = Material.TriangleFillMode;
  34522. this.name = name;
  34523. this.id = name || BABYLON.Tools.RandomId();
  34524. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34525. if (this._scene.useRightHandedSystem) {
  34526. this.sideOrientation = Material.ClockWiseSideOrientation;
  34527. }
  34528. else {
  34529. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34530. }
  34531. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34532. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34533. if (!doNotAdd) {
  34534. this._scene.materials.push(this);
  34535. }
  34536. }
  34537. Object.defineProperty(Material, "TriangleFillMode", {
  34538. /**
  34539. * Returns the triangle fill mode
  34540. */
  34541. get: function () {
  34542. return Material._TriangleFillMode;
  34543. },
  34544. enumerable: true,
  34545. configurable: true
  34546. });
  34547. Object.defineProperty(Material, "WireFrameFillMode", {
  34548. /**
  34549. * Returns the wireframe mode
  34550. */
  34551. get: function () {
  34552. return Material._WireFrameFillMode;
  34553. },
  34554. enumerable: true,
  34555. configurable: true
  34556. });
  34557. Object.defineProperty(Material, "PointFillMode", {
  34558. /**
  34559. * Returns the point fill mode
  34560. */
  34561. get: function () {
  34562. return Material._PointFillMode;
  34563. },
  34564. enumerable: true,
  34565. configurable: true
  34566. });
  34567. Object.defineProperty(Material, "PointListDrawMode", {
  34568. /**
  34569. * Returns the point list draw mode
  34570. */
  34571. get: function () {
  34572. return Material._PointListDrawMode;
  34573. },
  34574. enumerable: true,
  34575. configurable: true
  34576. });
  34577. Object.defineProperty(Material, "LineListDrawMode", {
  34578. /**
  34579. * Returns the line list draw mode
  34580. */
  34581. get: function () {
  34582. return Material._LineListDrawMode;
  34583. },
  34584. enumerable: true,
  34585. configurable: true
  34586. });
  34587. Object.defineProperty(Material, "LineLoopDrawMode", {
  34588. /**
  34589. * Returns the line loop draw mode
  34590. */
  34591. get: function () {
  34592. return Material._LineLoopDrawMode;
  34593. },
  34594. enumerable: true,
  34595. configurable: true
  34596. });
  34597. Object.defineProperty(Material, "LineStripDrawMode", {
  34598. /**
  34599. * Returns the line strip draw mode
  34600. */
  34601. get: function () {
  34602. return Material._LineStripDrawMode;
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34608. /**
  34609. * Returns the triangle strip draw mode
  34610. */
  34611. get: function () {
  34612. return Material._TriangleStripDrawMode;
  34613. },
  34614. enumerable: true,
  34615. configurable: true
  34616. });
  34617. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34618. /**
  34619. * Returns the triangle fan draw mode
  34620. */
  34621. get: function () {
  34622. return Material._TriangleFanDrawMode;
  34623. },
  34624. enumerable: true,
  34625. configurable: true
  34626. });
  34627. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34628. /**
  34629. * Returns the clock-wise side orientation
  34630. */
  34631. get: function () {
  34632. return Material._ClockWiseSideOrientation;
  34633. },
  34634. enumerable: true,
  34635. configurable: true
  34636. });
  34637. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34638. /**
  34639. * Returns the counter clock-wise side orientation
  34640. */
  34641. get: function () {
  34642. return Material._CounterClockWiseSideOrientation;
  34643. },
  34644. enumerable: true,
  34645. configurable: true
  34646. });
  34647. Object.defineProperty(Material, "TextureDirtyFlag", {
  34648. /**
  34649. * Returns the dirty texture flag value
  34650. */
  34651. get: function () {
  34652. return Material._TextureDirtyFlag;
  34653. },
  34654. enumerable: true,
  34655. configurable: true
  34656. });
  34657. Object.defineProperty(Material, "LightDirtyFlag", {
  34658. /**
  34659. * Returns the dirty light flag value
  34660. */
  34661. get: function () {
  34662. return Material._LightDirtyFlag;
  34663. },
  34664. enumerable: true,
  34665. configurable: true
  34666. });
  34667. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34668. /**
  34669. * Returns the dirty fresnel flag value
  34670. */
  34671. get: function () {
  34672. return Material._FresnelDirtyFlag;
  34673. },
  34674. enumerable: true,
  34675. configurable: true
  34676. });
  34677. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34678. /**
  34679. * Returns the dirty attributes flag value
  34680. */
  34681. get: function () {
  34682. return Material._AttributesDirtyFlag;
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. Object.defineProperty(Material, "MiscDirtyFlag", {
  34688. /**
  34689. * Returns the dirty misc flag value
  34690. */
  34691. get: function () {
  34692. return Material._MiscDirtyFlag;
  34693. },
  34694. enumerable: true,
  34695. configurable: true
  34696. });
  34697. Object.defineProperty(Material.prototype, "alpha", {
  34698. /**
  34699. * Gets the alpha value of the material
  34700. */
  34701. get: function () {
  34702. return this._alpha;
  34703. },
  34704. /**
  34705. * Sets the alpha value of the material
  34706. */
  34707. set: function (value) {
  34708. if (this._alpha === value) {
  34709. return;
  34710. }
  34711. this._alpha = value;
  34712. this.markAsDirty(Material.MiscDirtyFlag);
  34713. },
  34714. enumerable: true,
  34715. configurable: true
  34716. });
  34717. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34718. /**
  34719. * Gets the back-face culling state
  34720. */
  34721. get: function () {
  34722. return this._backFaceCulling;
  34723. },
  34724. /**
  34725. * Sets the back-face culling state
  34726. */
  34727. set: function (value) {
  34728. if (this._backFaceCulling === value) {
  34729. return;
  34730. }
  34731. this._backFaceCulling = value;
  34732. this.markAsDirty(Material.TextureDirtyFlag);
  34733. },
  34734. enumerable: true,
  34735. configurable: true
  34736. });
  34737. Object.defineProperty(Material.prototype, "onDispose", {
  34738. /**
  34739. * Called during a dispose event
  34740. */
  34741. set: function (callback) {
  34742. if (this._onDisposeObserver) {
  34743. this.onDisposeObservable.remove(this._onDisposeObserver);
  34744. }
  34745. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34746. },
  34747. enumerable: true,
  34748. configurable: true
  34749. });
  34750. Object.defineProperty(Material.prototype, "onBind", {
  34751. /**
  34752. * Called during a bind event
  34753. */
  34754. set: function (callback) {
  34755. if (this._onBindObserver) {
  34756. this.onBindObservable.remove(this._onBindObserver);
  34757. }
  34758. this._onBindObserver = this.onBindObservable.add(callback);
  34759. },
  34760. enumerable: true,
  34761. configurable: true
  34762. });
  34763. Object.defineProperty(Material.prototype, "alphaMode", {
  34764. /**
  34765. * Gets the value of the alpha mode
  34766. */
  34767. get: function () {
  34768. return this._alphaMode;
  34769. },
  34770. /**
  34771. * Sets the value of the alpha mode.
  34772. *
  34773. * | Value | Type | Description |
  34774. * | --- | --- | --- |
  34775. * | 0 | ALPHA_DISABLE | |
  34776. * | 1 | ALPHA_ADD | |
  34777. * | 2 | ALPHA_COMBINE | |
  34778. * | 3 | ALPHA_SUBTRACT | |
  34779. * | 4 | ALPHA_MULTIPLY | |
  34780. * | 5 | ALPHA_MAXIMIZED | |
  34781. * | 6 | ALPHA_ONEONE | |
  34782. * | 7 | ALPHA_PREMULTIPLIED | |
  34783. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34784. * | 9 | ALPHA_INTERPOLATE | |
  34785. * | 10 | ALPHA_SCREENMODE | |
  34786. *
  34787. */
  34788. set: function (value) {
  34789. if (this._alphaMode === value) {
  34790. return;
  34791. }
  34792. this._alphaMode = value;
  34793. this.markAsDirty(Material.TextureDirtyFlag);
  34794. },
  34795. enumerable: true,
  34796. configurable: true
  34797. });
  34798. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34799. /**
  34800. * Gets the depth pre-pass value
  34801. */
  34802. get: function () {
  34803. return this._needDepthPrePass;
  34804. },
  34805. /**
  34806. * Sets the need depth pre-pass value
  34807. */
  34808. set: function (value) {
  34809. if (this._needDepthPrePass === value) {
  34810. return;
  34811. }
  34812. this._needDepthPrePass = value;
  34813. if (this._needDepthPrePass) {
  34814. this.checkReadyOnEveryCall = true;
  34815. }
  34816. },
  34817. enumerable: true,
  34818. configurable: true
  34819. });
  34820. Object.defineProperty(Material.prototype, "fogEnabled", {
  34821. /**
  34822. * Gets the value of the fog enabled state
  34823. */
  34824. get: function () {
  34825. return this._fogEnabled;
  34826. },
  34827. /**
  34828. * Sets the state for enabling fog
  34829. */
  34830. set: function (value) {
  34831. if (this._fogEnabled === value) {
  34832. return;
  34833. }
  34834. this._fogEnabled = value;
  34835. this.markAsDirty(Material.MiscDirtyFlag);
  34836. },
  34837. enumerable: true,
  34838. configurable: true
  34839. });
  34840. Object.defineProperty(Material.prototype, "wireframe", {
  34841. /**
  34842. * Gets a value specifying if wireframe mode is enabled
  34843. */
  34844. get: function () {
  34845. switch (this._fillMode) {
  34846. case Material.WireFrameFillMode:
  34847. case Material.LineListDrawMode:
  34848. case Material.LineLoopDrawMode:
  34849. case Material.LineStripDrawMode:
  34850. return true;
  34851. }
  34852. return this._scene.forceWireframe;
  34853. },
  34854. /**
  34855. * Sets the state of wireframe mode
  34856. */
  34857. set: function (value) {
  34858. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34859. },
  34860. enumerable: true,
  34861. configurable: true
  34862. });
  34863. Object.defineProperty(Material.prototype, "pointsCloud", {
  34864. /**
  34865. * Gets the value specifying if point clouds are enabled
  34866. */
  34867. get: function () {
  34868. switch (this._fillMode) {
  34869. case Material.PointFillMode:
  34870. case Material.PointListDrawMode:
  34871. return true;
  34872. }
  34873. return this._scene.forcePointsCloud;
  34874. },
  34875. /**
  34876. * Sets the state of point cloud mode
  34877. */
  34878. set: function (value) {
  34879. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34880. },
  34881. enumerable: true,
  34882. configurable: true
  34883. });
  34884. Object.defineProperty(Material.prototype, "fillMode", {
  34885. /**
  34886. * Gets the material fill mode
  34887. */
  34888. get: function () {
  34889. return this._fillMode;
  34890. },
  34891. /**
  34892. * Sets the material fill mode
  34893. */
  34894. set: function (value) {
  34895. if (this._fillMode === value) {
  34896. return;
  34897. }
  34898. this._fillMode = value;
  34899. this.markAsDirty(Material.MiscDirtyFlag);
  34900. },
  34901. enumerable: true,
  34902. configurable: true
  34903. });
  34904. /**
  34905. * Returns a string representation of the current material
  34906. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34907. * @returns a string with material information
  34908. */
  34909. Material.prototype.toString = function (fullDetails) {
  34910. var ret = "Name: " + this.name;
  34911. if (fullDetails) {
  34912. }
  34913. return ret;
  34914. };
  34915. /**
  34916. * Gets the class name of the material
  34917. * @returns a string with the class name of the material
  34918. */
  34919. Material.prototype.getClassName = function () {
  34920. return "Material";
  34921. };
  34922. Object.defineProperty(Material.prototype, "isFrozen", {
  34923. /**
  34924. * Specifies if updates for the material been locked
  34925. */
  34926. get: function () {
  34927. return this.checkReadyOnlyOnce;
  34928. },
  34929. enumerable: true,
  34930. configurable: true
  34931. });
  34932. /**
  34933. * Locks updates for the material
  34934. */
  34935. Material.prototype.freeze = function () {
  34936. this.checkReadyOnlyOnce = true;
  34937. };
  34938. /**
  34939. * Unlocks updates for the material
  34940. */
  34941. Material.prototype.unfreeze = function () {
  34942. this.checkReadyOnlyOnce = false;
  34943. };
  34944. /**
  34945. * Specifies if the material is ready to be used
  34946. * @param mesh defines the mesh to check
  34947. * @param useInstances specifies if instances should be used
  34948. * @returns a boolean indicating if the material is ready to be used
  34949. */
  34950. Material.prototype.isReady = function (mesh, useInstances) {
  34951. return true;
  34952. };
  34953. /**
  34954. * Specifies that the submesh is ready to be used
  34955. * @param mesh defines the mesh to check
  34956. * @param subMesh defines which submesh to check
  34957. * @param useInstances specifies that instances should be used
  34958. * @returns a boolean indicating that the submesh is ready or not
  34959. */
  34960. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34961. return false;
  34962. };
  34963. /**
  34964. * Returns the material effect
  34965. * @returns the effect associated with the material
  34966. */
  34967. Material.prototype.getEffect = function () {
  34968. return this._effect;
  34969. };
  34970. /**
  34971. * Returns the current scene
  34972. * @returns a Scene
  34973. */
  34974. Material.prototype.getScene = function () {
  34975. return this._scene;
  34976. };
  34977. /**
  34978. * Specifies if the material will require alpha blending
  34979. * @returns a boolean specifying if alpha blending is needed
  34980. */
  34981. Material.prototype.needAlphaBlending = function () {
  34982. return (this.alpha < 1.0);
  34983. };
  34984. /**
  34985. * Specifies if the mesh will require alpha blending
  34986. * @param mesh defines the mesh to check
  34987. * @returns a boolean specifying if alpha blending is needed for the mesh
  34988. */
  34989. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34990. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34991. };
  34992. /**
  34993. * Specifies if this material should be rendered in alpha test mode
  34994. * @returns a boolean specifying if an alpha test is needed.
  34995. */
  34996. Material.prototype.needAlphaTesting = function () {
  34997. return false;
  34998. };
  34999. /**
  35000. * Gets the texture used for the alpha test
  35001. * @returns the texture to use for alpha testing
  35002. */
  35003. Material.prototype.getAlphaTestTexture = function () {
  35004. return null;
  35005. };
  35006. /**
  35007. * Marks the material to indicate that it needs to be re-calculated
  35008. */
  35009. Material.prototype.markDirty = function () {
  35010. this._wasPreviouslyReady = false;
  35011. };
  35012. /** @hidden */
  35013. Material.prototype._preBind = function (effect, overrideOrientation) {
  35014. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35015. var engine = this._scene.getEngine();
  35016. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35017. var reverse = orientation === Material.ClockWiseSideOrientation;
  35018. engine.enableEffect(effect ? effect : this._effect);
  35019. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35020. return reverse;
  35021. };
  35022. /**
  35023. * Binds the material to the mesh
  35024. * @param world defines the world transformation matrix
  35025. * @param mesh defines the mesh to bind the material to
  35026. */
  35027. Material.prototype.bind = function (world, mesh) {
  35028. };
  35029. /**
  35030. * Binds the submesh to the material
  35031. * @param world defines the world transformation matrix
  35032. * @param mesh defines the mesh containing the submesh
  35033. * @param subMesh defines the submesh to bind the material to
  35034. */
  35035. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35036. };
  35037. /**
  35038. * Binds the world matrix to the material
  35039. * @param world defines the world transformation matrix
  35040. */
  35041. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35042. };
  35043. /**
  35044. * Binds the scene's uniform buffer to the effect.
  35045. * @param effect defines the effect to bind to the scene uniform buffer
  35046. * @param sceneUbo defines the uniform buffer storing scene data
  35047. */
  35048. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35049. sceneUbo.bindToEffect(effect, "Scene");
  35050. };
  35051. /**
  35052. * Binds the view matrix to the effect
  35053. * @param effect defines the effect to bind the view matrix to
  35054. */
  35055. Material.prototype.bindView = function (effect) {
  35056. if (!this._useUBO) {
  35057. effect.setMatrix("view", this.getScene().getViewMatrix());
  35058. }
  35059. else {
  35060. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35061. }
  35062. };
  35063. /**
  35064. * Binds the view projection matrix to the effect
  35065. * @param effect defines the effect to bind the view projection matrix to
  35066. */
  35067. Material.prototype.bindViewProjection = function (effect) {
  35068. if (!this._useUBO) {
  35069. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35070. }
  35071. else {
  35072. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35073. }
  35074. };
  35075. /**
  35076. * Specifies if material alpha testing should be turned on for the mesh
  35077. * @param mesh defines the mesh to check
  35078. */
  35079. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35080. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35081. };
  35082. /**
  35083. * Processes to execute after binding the material to a mesh
  35084. * @param mesh defines the rendered mesh
  35085. */
  35086. Material.prototype._afterBind = function (mesh) {
  35087. this._scene._cachedMaterial = this;
  35088. if (mesh) {
  35089. this._scene._cachedVisibility = mesh.visibility;
  35090. }
  35091. else {
  35092. this._scene._cachedVisibility = 1;
  35093. }
  35094. if (mesh) {
  35095. this.onBindObservable.notifyObservers(mesh);
  35096. }
  35097. if (this.disableDepthWrite) {
  35098. var engine = this._scene.getEngine();
  35099. this._cachedDepthWriteState = engine.getDepthWrite();
  35100. engine.setDepthWrite(false);
  35101. }
  35102. };
  35103. /**
  35104. * Unbinds the material from the mesh
  35105. */
  35106. Material.prototype.unbind = function () {
  35107. this.onUnBindObservable.notifyObservers(this);
  35108. if (this.disableDepthWrite) {
  35109. var engine = this._scene.getEngine();
  35110. engine.setDepthWrite(this._cachedDepthWriteState);
  35111. }
  35112. };
  35113. /**
  35114. * Gets the active textures from the material
  35115. * @returns an array of textures
  35116. */
  35117. Material.prototype.getActiveTextures = function () {
  35118. return [];
  35119. };
  35120. /**
  35121. * Specifies if the material uses a texture
  35122. * @param texture defines the texture to check against the material
  35123. * @returns a boolean specifying if the material uses the texture
  35124. */
  35125. Material.prototype.hasTexture = function (texture) {
  35126. return false;
  35127. };
  35128. /**
  35129. * Makes a duplicate of the material, and gives it a new name
  35130. * @param name defines the new name for the duplicated material
  35131. * @returns the cloned material
  35132. */
  35133. Material.prototype.clone = function (name) {
  35134. return null;
  35135. };
  35136. /**
  35137. * Gets the meshes bound to the material
  35138. * @returns an array of meshes bound to the material
  35139. */
  35140. Material.prototype.getBindedMeshes = function () {
  35141. var result = new Array();
  35142. for (var index = 0; index < this._scene.meshes.length; index++) {
  35143. var mesh = this._scene.meshes[index];
  35144. if (mesh.material === this) {
  35145. result.push(mesh);
  35146. }
  35147. }
  35148. return result;
  35149. };
  35150. /**
  35151. * Force shader compilation
  35152. * @param mesh defines the mesh associated with this material
  35153. * @param onCompiled defines a function to execute once the material is compiled
  35154. * @param options defines the options to configure the compilation
  35155. */
  35156. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35157. var _this = this;
  35158. var localOptions = __assign({ clipPlane: false }, options);
  35159. var subMesh = new BABYLON.BaseSubMesh();
  35160. var scene = this.getScene();
  35161. var checkReady = function () {
  35162. if (!_this._scene || !_this._scene.getEngine()) {
  35163. return;
  35164. }
  35165. if (subMesh._materialDefines) {
  35166. subMesh._materialDefines._renderId = -1;
  35167. }
  35168. var clipPlaneState = scene.clipPlane;
  35169. if (localOptions.clipPlane) {
  35170. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35171. }
  35172. if (_this.storeEffectOnSubMeshes) {
  35173. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35174. if (onCompiled) {
  35175. onCompiled(_this);
  35176. }
  35177. }
  35178. else {
  35179. setTimeout(checkReady, 16);
  35180. }
  35181. }
  35182. else {
  35183. if (_this.isReady(mesh)) {
  35184. if (onCompiled) {
  35185. onCompiled(_this);
  35186. }
  35187. }
  35188. else {
  35189. setTimeout(checkReady, 16);
  35190. }
  35191. }
  35192. if (localOptions.clipPlane) {
  35193. scene.clipPlane = clipPlaneState;
  35194. }
  35195. };
  35196. checkReady();
  35197. };
  35198. /**
  35199. * Force shader compilation
  35200. * @param mesh defines the mesh that will use this material
  35201. * @param options defines additional options for compiling the shaders
  35202. * @returns a promise that resolves when the compilation completes
  35203. */
  35204. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35205. var _this = this;
  35206. return new Promise(function (resolve) {
  35207. _this.forceCompilation(mesh, function () {
  35208. resolve();
  35209. }, options);
  35210. });
  35211. };
  35212. /**
  35213. * Marks a define in the material to indicate that it needs to be re-computed
  35214. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35215. */
  35216. Material.prototype.markAsDirty = function (flag) {
  35217. if (flag & Material.TextureDirtyFlag) {
  35218. this._markAllSubMeshesAsTexturesDirty();
  35219. }
  35220. if (flag & Material.LightDirtyFlag) {
  35221. this._markAllSubMeshesAsLightsDirty();
  35222. }
  35223. if (flag & Material.FresnelDirtyFlag) {
  35224. this._markAllSubMeshesAsFresnelDirty();
  35225. }
  35226. if (flag & Material.AttributesDirtyFlag) {
  35227. this._markAllSubMeshesAsAttributesDirty();
  35228. }
  35229. if (flag & Material.MiscDirtyFlag) {
  35230. this._markAllSubMeshesAsMiscDirty();
  35231. }
  35232. this.getScene().resetCachedMaterial();
  35233. };
  35234. /**
  35235. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35236. * @param func defines a function which checks material defines against the submeshes
  35237. */
  35238. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35239. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35240. var mesh = _a[_i];
  35241. if (!mesh.subMeshes) {
  35242. continue;
  35243. }
  35244. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35245. var subMesh = _c[_b];
  35246. if (subMesh.getMaterial() !== this) {
  35247. continue;
  35248. }
  35249. if (!subMesh._materialDefines) {
  35250. continue;
  35251. }
  35252. func(subMesh._materialDefines);
  35253. }
  35254. }
  35255. };
  35256. /**
  35257. * Indicates that image processing needs to be re-calculated for all submeshes
  35258. */
  35259. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35260. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35261. };
  35262. /**
  35263. * Indicates that textures need to be re-calculated for all submeshes
  35264. */
  35265. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35266. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35267. };
  35268. /**
  35269. * Indicates that fresnel needs to be re-calculated for all submeshes
  35270. */
  35271. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35272. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35273. };
  35274. /**
  35275. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35276. */
  35277. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35278. this._markAllSubMeshesAsDirty(function (defines) {
  35279. defines.markAsFresnelDirty();
  35280. defines.markAsMiscDirty();
  35281. });
  35282. };
  35283. /**
  35284. * Indicates that lights need to be re-calculated for all submeshes
  35285. */
  35286. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35287. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35288. };
  35289. /**
  35290. * Indicates that attributes need to be re-calculated for all submeshes
  35291. */
  35292. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35293. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35294. };
  35295. /**
  35296. * Indicates that misc needs to be re-calculated for all submeshes
  35297. */
  35298. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35299. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35300. };
  35301. /**
  35302. * Indicates that textures and misc need to be re-calculated for all submeshes
  35303. */
  35304. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35305. this._markAllSubMeshesAsDirty(function (defines) {
  35306. defines.markAsTexturesDirty();
  35307. defines.markAsMiscDirty();
  35308. });
  35309. };
  35310. /**
  35311. * Disposes the material
  35312. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35313. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35314. */
  35315. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35316. // Animations
  35317. this.getScene().stopAnimation(this);
  35318. this.getScene().freeProcessedMaterials();
  35319. // Remove from scene
  35320. var index = this._scene.materials.indexOf(this);
  35321. if (index >= 0) {
  35322. this._scene.materials.splice(index, 1);
  35323. }
  35324. // Remove from meshes
  35325. for (index = 0; index < this._scene.meshes.length; index++) {
  35326. var mesh = this._scene.meshes[index];
  35327. if (mesh.material === this) {
  35328. mesh.material = null;
  35329. if (mesh.geometry) {
  35330. var geometry = (mesh.geometry);
  35331. if (this.storeEffectOnSubMeshes) {
  35332. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35333. var subMesh = _a[_i];
  35334. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35335. if (forceDisposeEffect && subMesh._materialEffect) {
  35336. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35337. }
  35338. }
  35339. }
  35340. else {
  35341. geometry._releaseVertexArrayObject(this._effect);
  35342. }
  35343. }
  35344. }
  35345. }
  35346. this._uniformBuffer.dispose();
  35347. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35348. if (forceDisposeEffect && this._effect) {
  35349. if (!this.storeEffectOnSubMeshes) {
  35350. this._scene.getEngine()._releaseEffect(this._effect);
  35351. }
  35352. this._effect = null;
  35353. }
  35354. // Callback
  35355. this.onDisposeObservable.notifyObservers(this);
  35356. this.onDisposeObservable.clear();
  35357. this.onBindObservable.clear();
  35358. this.onUnBindObservable.clear();
  35359. };
  35360. /**
  35361. * Serializes this material
  35362. * @returns the serialized material object
  35363. */
  35364. Material.prototype.serialize = function () {
  35365. return BABYLON.SerializationHelper.Serialize(this);
  35366. };
  35367. /**
  35368. * Creates a MultiMaterial from parsed MultiMaterial data.
  35369. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35370. * @param scene defines the hosting scene
  35371. * @returns a new MultiMaterial
  35372. */
  35373. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35374. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35375. multiMaterial.id = parsedMultiMaterial.id;
  35376. if (BABYLON.Tags) {
  35377. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35378. }
  35379. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35380. var subMatId = parsedMultiMaterial.materials[matIndex];
  35381. if (subMatId) {
  35382. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35383. }
  35384. else {
  35385. multiMaterial.subMaterials.push(null);
  35386. }
  35387. }
  35388. return multiMaterial;
  35389. };
  35390. /**
  35391. * Creates a material from parsed material data
  35392. * @param parsedMaterial defines parsed material data
  35393. * @param scene defines the hosting scene
  35394. * @param rootUrl defines the root URL to use to load textures
  35395. * @returns a new material
  35396. */
  35397. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35398. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35399. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35400. }
  35401. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35402. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35403. if (!BABYLON.LegacyPBRMaterial) {
  35404. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35405. return;
  35406. }
  35407. }
  35408. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35409. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35410. };
  35411. // Triangle views
  35412. Material._TriangleFillMode = 0;
  35413. Material._WireFrameFillMode = 1;
  35414. Material._PointFillMode = 2;
  35415. // Draw modes
  35416. Material._PointListDrawMode = 3;
  35417. Material._LineListDrawMode = 4;
  35418. Material._LineLoopDrawMode = 5;
  35419. Material._LineStripDrawMode = 6;
  35420. Material._TriangleStripDrawMode = 7;
  35421. Material._TriangleFanDrawMode = 8;
  35422. /**
  35423. * Stores the clock-wise side orientation
  35424. */
  35425. Material._ClockWiseSideOrientation = 0;
  35426. /**
  35427. * Stores the counter clock-wise side orientation
  35428. */
  35429. Material._CounterClockWiseSideOrientation = 1;
  35430. /**
  35431. * The dirty texture flag value
  35432. */
  35433. Material._TextureDirtyFlag = 1;
  35434. /**
  35435. * The dirty light flag value
  35436. */
  35437. Material._LightDirtyFlag = 2;
  35438. /**
  35439. * The dirty fresnel flag value
  35440. */
  35441. Material._FresnelDirtyFlag = 4;
  35442. /**
  35443. * The dirty attribute flag value
  35444. */
  35445. Material._AttributesDirtyFlag = 8;
  35446. /**
  35447. * The dirty misc flag value
  35448. */
  35449. Material._MiscDirtyFlag = 16;
  35450. __decorate([
  35451. BABYLON.serialize()
  35452. ], Material.prototype, "id", void 0);
  35453. __decorate([
  35454. BABYLON.serialize()
  35455. ], Material.prototype, "name", void 0);
  35456. __decorate([
  35457. BABYLON.serialize()
  35458. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35459. __decorate([
  35460. BABYLON.serialize()
  35461. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35462. __decorate([
  35463. BABYLON.serialize()
  35464. ], Material.prototype, "state", void 0);
  35465. __decorate([
  35466. BABYLON.serialize("alpha")
  35467. ], Material.prototype, "_alpha", void 0);
  35468. __decorate([
  35469. BABYLON.serialize("backFaceCulling")
  35470. ], Material.prototype, "_backFaceCulling", void 0);
  35471. __decorate([
  35472. BABYLON.serialize()
  35473. ], Material.prototype, "sideOrientation", void 0);
  35474. __decorate([
  35475. BABYLON.serialize("alphaMode")
  35476. ], Material.prototype, "_alphaMode", void 0);
  35477. __decorate([
  35478. BABYLON.serialize()
  35479. ], Material.prototype, "_needDepthPrePass", void 0);
  35480. __decorate([
  35481. BABYLON.serialize()
  35482. ], Material.prototype, "disableDepthWrite", void 0);
  35483. __decorate([
  35484. BABYLON.serialize()
  35485. ], Material.prototype, "forceDepthWrite", void 0);
  35486. __decorate([
  35487. BABYLON.serialize()
  35488. ], Material.prototype, "separateCullingPass", void 0);
  35489. __decorate([
  35490. BABYLON.serialize("fogEnabled")
  35491. ], Material.prototype, "_fogEnabled", void 0);
  35492. __decorate([
  35493. BABYLON.serialize()
  35494. ], Material.prototype, "pointSize", void 0);
  35495. __decorate([
  35496. BABYLON.serialize()
  35497. ], Material.prototype, "zOffset", void 0);
  35498. __decorate([
  35499. BABYLON.serialize()
  35500. ], Material.prototype, "wireframe", null);
  35501. __decorate([
  35502. BABYLON.serialize()
  35503. ], Material.prototype, "pointsCloud", null);
  35504. __decorate([
  35505. BABYLON.serialize()
  35506. ], Material.prototype, "fillMode", null);
  35507. return Material;
  35508. }());
  35509. BABYLON.Material = Material;
  35510. })(BABYLON || (BABYLON = {}));
  35511. //# sourceMappingURL=babylon.material.js.map
  35512. var BABYLON;
  35513. (function (BABYLON) {
  35514. var UniformBuffer = /** @class */ (function () {
  35515. /**
  35516. * Uniform buffer objects.
  35517. *
  35518. * Handles blocks of uniform on the GPU.
  35519. *
  35520. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35521. *
  35522. * For more information, please refer to :
  35523. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35524. */
  35525. function UniformBuffer(engine, data, dynamic) {
  35526. this._engine = engine;
  35527. this._noUBO = !engine.supportsUniformBuffers;
  35528. this._dynamic = dynamic;
  35529. this._data = data || [];
  35530. this._uniformLocations = {};
  35531. this._uniformSizes = {};
  35532. this._uniformLocationPointer = 0;
  35533. this._needSync = false;
  35534. if (this._noUBO) {
  35535. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35536. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35537. this.updateFloat = this._updateFloatForEffect;
  35538. this.updateFloat2 = this._updateFloat2ForEffect;
  35539. this.updateFloat3 = this._updateFloat3ForEffect;
  35540. this.updateFloat4 = this._updateFloat4ForEffect;
  35541. this.updateMatrix = this._updateMatrixForEffect;
  35542. this.updateVector3 = this._updateVector3ForEffect;
  35543. this.updateVector4 = this._updateVector4ForEffect;
  35544. this.updateColor3 = this._updateColor3ForEffect;
  35545. this.updateColor4 = this._updateColor4ForEffect;
  35546. }
  35547. else {
  35548. this._engine._uniformBuffers.push(this);
  35549. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35550. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35551. this.updateFloat = this._updateFloatForUniform;
  35552. this.updateFloat2 = this._updateFloat2ForUniform;
  35553. this.updateFloat3 = this._updateFloat3ForUniform;
  35554. this.updateFloat4 = this._updateFloat4ForUniform;
  35555. this.updateMatrix = this._updateMatrixForUniform;
  35556. this.updateVector3 = this._updateVector3ForUniform;
  35557. this.updateVector4 = this._updateVector4ForUniform;
  35558. this.updateColor3 = this._updateColor3ForUniform;
  35559. this.updateColor4 = this._updateColor4ForUniform;
  35560. }
  35561. }
  35562. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35563. // Properties
  35564. /**
  35565. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35566. * or just falling back on setUniformXXX calls.
  35567. */
  35568. get: function () {
  35569. return !this._noUBO;
  35570. },
  35571. enumerable: true,
  35572. configurable: true
  35573. });
  35574. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35575. /**
  35576. * Indicates if the WebGL underlying uniform buffer is in sync
  35577. * with the javascript cache data.
  35578. */
  35579. get: function () {
  35580. return !this._needSync;
  35581. },
  35582. enumerable: true,
  35583. configurable: true
  35584. });
  35585. /**
  35586. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35587. * Also, a dynamic UniformBuffer will disable cache verification and always
  35588. * update the underlying WebGL uniform buffer to the GPU.
  35589. */
  35590. UniformBuffer.prototype.isDynamic = function () {
  35591. return this._dynamic !== undefined;
  35592. };
  35593. /**
  35594. * The data cache on JS side.
  35595. */
  35596. UniformBuffer.prototype.getData = function () {
  35597. return this._bufferData;
  35598. };
  35599. /**
  35600. * The underlying WebGL Uniform buffer.
  35601. */
  35602. UniformBuffer.prototype.getBuffer = function () {
  35603. return this._buffer;
  35604. };
  35605. /**
  35606. * std140 layout specifies how to align data within an UBO structure.
  35607. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35608. * for specs.
  35609. */
  35610. UniformBuffer.prototype._fillAlignment = function (size) {
  35611. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35612. // and 4x4 matrices
  35613. // TODO : change if other types are used
  35614. var alignment;
  35615. if (size <= 2) {
  35616. alignment = size;
  35617. }
  35618. else {
  35619. alignment = 4;
  35620. }
  35621. if ((this._uniformLocationPointer % alignment) !== 0) {
  35622. var oldPointer = this._uniformLocationPointer;
  35623. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35624. var diff = this._uniformLocationPointer - oldPointer;
  35625. for (var i = 0; i < diff; i++) {
  35626. this._data.push(0);
  35627. }
  35628. }
  35629. };
  35630. /**
  35631. * Adds an uniform in the buffer.
  35632. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35633. * for the layout to be correct !
  35634. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35635. * @param {number|number[]} size Data size, or data directly.
  35636. */
  35637. UniformBuffer.prototype.addUniform = function (name, size) {
  35638. if (this._noUBO) {
  35639. return;
  35640. }
  35641. if (this._uniformLocations[name] !== undefined) {
  35642. // Already existing uniform
  35643. return;
  35644. }
  35645. // This function must be called in the order of the shader layout !
  35646. // size can be the size of the uniform, or data directly
  35647. var data;
  35648. if (size instanceof Array) {
  35649. data = size;
  35650. size = data.length;
  35651. }
  35652. else {
  35653. size = size;
  35654. data = [];
  35655. // Fill with zeros
  35656. for (var i = 0; i < size; i++) {
  35657. data.push(0);
  35658. }
  35659. }
  35660. this._fillAlignment(size);
  35661. this._uniformSizes[name] = size;
  35662. this._uniformLocations[name] = this._uniformLocationPointer;
  35663. this._uniformLocationPointer += size;
  35664. for (var i = 0; i < size; i++) {
  35665. this._data.push(data[i]);
  35666. }
  35667. this._needSync = true;
  35668. };
  35669. /**
  35670. * Wrapper for addUniform.
  35671. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35672. * @param {Matrix} mat A 4x4 matrix.
  35673. */
  35674. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35675. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35676. };
  35677. /**
  35678. * Wrapper for addUniform.
  35679. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35680. * @param {number} x
  35681. * @param {number} y
  35682. */
  35683. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35684. var temp = [x, y];
  35685. this.addUniform(name, temp);
  35686. };
  35687. /**
  35688. * Wrapper for addUniform.
  35689. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35690. * @param {number} x
  35691. * @param {number} y
  35692. * @param {number} z
  35693. */
  35694. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35695. var temp = [x, y, z];
  35696. this.addUniform(name, temp);
  35697. };
  35698. /**
  35699. * Wrapper for addUniform.
  35700. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35701. * @param {Color3} color
  35702. */
  35703. UniformBuffer.prototype.addColor3 = function (name, color) {
  35704. var temp = new Array();
  35705. color.toArray(temp);
  35706. this.addUniform(name, temp);
  35707. };
  35708. /**
  35709. * Wrapper for addUniform.
  35710. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35711. * @param {Color3} color
  35712. * @param {number} alpha
  35713. */
  35714. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35715. var temp = new Array();
  35716. color.toArray(temp);
  35717. temp.push(alpha);
  35718. this.addUniform(name, temp);
  35719. };
  35720. /**
  35721. * Wrapper for addUniform.
  35722. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35723. * @param {Vector3} vector
  35724. */
  35725. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35726. var temp = new Array();
  35727. vector.toArray(temp);
  35728. this.addUniform(name, temp);
  35729. };
  35730. /**
  35731. * Wrapper for addUniform.
  35732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35733. */
  35734. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35735. this.addUniform(name, 12);
  35736. };
  35737. /**
  35738. * Wrapper for addUniform.
  35739. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35740. */
  35741. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35742. this.addUniform(name, 8);
  35743. };
  35744. /**
  35745. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35746. */
  35747. UniformBuffer.prototype.create = function () {
  35748. if (this._noUBO) {
  35749. return;
  35750. }
  35751. if (this._buffer) {
  35752. return; // nothing to do
  35753. }
  35754. // See spec, alignment must be filled as a vec4
  35755. this._fillAlignment(4);
  35756. this._bufferData = new Float32Array(this._data);
  35757. this._rebuild();
  35758. this._needSync = true;
  35759. };
  35760. UniformBuffer.prototype._rebuild = function () {
  35761. if (this._noUBO) {
  35762. return;
  35763. }
  35764. if (this._dynamic) {
  35765. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35766. }
  35767. else {
  35768. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35769. }
  35770. };
  35771. /**
  35772. * Updates the WebGL Uniform Buffer on the GPU.
  35773. * If the `dynamic` flag is set to true, no cache comparison is done.
  35774. * Otherwise, the buffer will be updated only if the cache differs.
  35775. */
  35776. UniformBuffer.prototype.update = function () {
  35777. if (!this._buffer) {
  35778. this.create();
  35779. return;
  35780. }
  35781. if (!this._dynamic && !this._needSync) {
  35782. return;
  35783. }
  35784. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35785. this._needSync = false;
  35786. };
  35787. /**
  35788. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35789. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35790. * @param {number[]|Float32Array} data Flattened data
  35791. * @param {number} size Size of the data.
  35792. */
  35793. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35794. var location = this._uniformLocations[uniformName];
  35795. if (location === undefined) {
  35796. if (this._buffer) {
  35797. // Cannot add an uniform if the buffer is already created
  35798. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35799. return;
  35800. }
  35801. this.addUniform(uniformName, size);
  35802. location = this._uniformLocations[uniformName];
  35803. }
  35804. if (!this._buffer) {
  35805. this.create();
  35806. }
  35807. if (!this._dynamic) {
  35808. // Cache for static uniform buffers
  35809. var changed = false;
  35810. for (var i = 0; i < size; i++) {
  35811. if (this._bufferData[location + i] !== data[i]) {
  35812. changed = true;
  35813. this._bufferData[location + i] = data[i];
  35814. }
  35815. }
  35816. this._needSync = this._needSync || changed;
  35817. }
  35818. else {
  35819. // No cache for dynamic
  35820. for (var i = 0; i < size; i++) {
  35821. this._bufferData[location + i] = data[i];
  35822. }
  35823. }
  35824. };
  35825. // Update methods
  35826. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35827. // To match std140, matrix must be realigned
  35828. for (var i = 0; i < 3; i++) {
  35829. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35830. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35831. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35832. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35833. }
  35834. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35835. };
  35836. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35837. this._currentEffect.setMatrix3x3(name, matrix);
  35838. };
  35839. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35840. this._currentEffect.setMatrix2x2(name, matrix);
  35841. };
  35842. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35843. // To match std140, matrix must be realigned
  35844. for (var i = 0; i < 2; i++) {
  35845. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35846. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35847. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35848. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35849. }
  35850. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35851. };
  35852. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35853. this._currentEffect.setFloat(name, x);
  35854. };
  35855. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35856. UniformBuffer._tempBuffer[0] = x;
  35857. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35858. };
  35859. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35860. if (suffix === void 0) { suffix = ""; }
  35861. this._currentEffect.setFloat2(name + suffix, x, y);
  35862. };
  35863. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35864. if (suffix === void 0) { suffix = ""; }
  35865. UniformBuffer._tempBuffer[0] = x;
  35866. UniformBuffer._tempBuffer[1] = y;
  35867. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35868. };
  35869. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35870. if (suffix === void 0) { suffix = ""; }
  35871. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35872. };
  35873. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35874. if (suffix === void 0) { suffix = ""; }
  35875. UniformBuffer._tempBuffer[0] = x;
  35876. UniformBuffer._tempBuffer[1] = y;
  35877. UniformBuffer._tempBuffer[2] = z;
  35878. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35879. };
  35880. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35881. if (suffix === void 0) { suffix = ""; }
  35882. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35883. };
  35884. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35885. if (suffix === void 0) { suffix = ""; }
  35886. UniformBuffer._tempBuffer[0] = x;
  35887. UniformBuffer._tempBuffer[1] = y;
  35888. UniformBuffer._tempBuffer[2] = z;
  35889. UniformBuffer._tempBuffer[3] = w;
  35890. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35891. };
  35892. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35893. this._currentEffect.setMatrix(name, mat);
  35894. };
  35895. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35896. this.updateUniform(name, mat.toArray(), 16);
  35897. };
  35898. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35899. this._currentEffect.setVector3(name, vector);
  35900. };
  35901. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35902. vector.toArray(UniformBuffer._tempBuffer);
  35903. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35904. };
  35905. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35906. this._currentEffect.setVector4(name, vector);
  35907. };
  35908. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35909. vector.toArray(UniformBuffer._tempBuffer);
  35910. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35911. };
  35912. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35913. if (suffix === void 0) { suffix = ""; }
  35914. this._currentEffect.setColor3(name + suffix, color);
  35915. };
  35916. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35917. if (suffix === void 0) { suffix = ""; }
  35918. color.toArray(UniformBuffer._tempBuffer);
  35919. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35920. };
  35921. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35922. if (suffix === void 0) { suffix = ""; }
  35923. this._currentEffect.setColor4(name + suffix, color, alpha);
  35924. };
  35925. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35926. if (suffix === void 0) { suffix = ""; }
  35927. color.toArray(UniformBuffer._tempBuffer);
  35928. UniformBuffer._tempBuffer[3] = alpha;
  35929. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35930. };
  35931. /**
  35932. * Sets a sampler uniform on the effect.
  35933. * @param {string} name Name of the sampler.
  35934. * @param {Texture} texture
  35935. */
  35936. UniformBuffer.prototype.setTexture = function (name, texture) {
  35937. this._currentEffect.setTexture(name, texture);
  35938. };
  35939. /**
  35940. * Directly updates the value of the uniform in the cache AND on the GPU.
  35941. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35942. * @param {number[]|Float32Array} data Flattened data
  35943. */
  35944. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35945. this.updateUniform(uniformName, data, data.length);
  35946. this.update();
  35947. };
  35948. /**
  35949. * Binds this uniform buffer to an effect.
  35950. * @param {Effect} effect
  35951. * @param {string} name Name of the uniform block in the shader.
  35952. */
  35953. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35954. this._currentEffect = effect;
  35955. if (this._noUBO || !this._buffer) {
  35956. return;
  35957. }
  35958. effect.bindUniformBuffer(this._buffer, name);
  35959. };
  35960. /**
  35961. * Disposes the uniform buffer.
  35962. */
  35963. UniformBuffer.prototype.dispose = function () {
  35964. if (this._noUBO) {
  35965. return;
  35966. }
  35967. var index = this._engine._uniformBuffers.indexOf(this);
  35968. if (index !== -1) {
  35969. this._engine._uniformBuffers.splice(index, 1);
  35970. }
  35971. if (!this._buffer) {
  35972. return;
  35973. }
  35974. if (this._engine._releaseBuffer(this._buffer)) {
  35975. this._buffer = null;
  35976. }
  35977. };
  35978. // Pool for avoiding memory leaks
  35979. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35980. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35981. return UniformBuffer;
  35982. }());
  35983. BABYLON.UniformBuffer = UniformBuffer;
  35984. })(BABYLON || (BABYLON = {}));
  35985. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35986. var BABYLON;
  35987. (function (BABYLON) {
  35988. /**
  35989. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35990. */
  35991. var VertexData = /** @class */ (function () {
  35992. function VertexData() {
  35993. }
  35994. /**
  35995. * Uses the passed data array to set the set the values for the specified kind of data
  35996. * @param data a linear array of floating numbers
  35997. * @param kind the type of data that is being set, eg positions, colors etc
  35998. */
  35999. VertexData.prototype.set = function (data, kind) {
  36000. switch (kind) {
  36001. case BABYLON.VertexBuffer.PositionKind:
  36002. this.positions = data;
  36003. break;
  36004. case BABYLON.VertexBuffer.NormalKind:
  36005. this.normals = data;
  36006. break;
  36007. case BABYLON.VertexBuffer.TangentKind:
  36008. this.tangents = data;
  36009. break;
  36010. case BABYLON.VertexBuffer.UVKind:
  36011. this.uvs = data;
  36012. break;
  36013. case BABYLON.VertexBuffer.UV2Kind:
  36014. this.uvs2 = data;
  36015. break;
  36016. case BABYLON.VertexBuffer.UV3Kind:
  36017. this.uvs3 = data;
  36018. break;
  36019. case BABYLON.VertexBuffer.UV4Kind:
  36020. this.uvs4 = data;
  36021. break;
  36022. case BABYLON.VertexBuffer.UV5Kind:
  36023. this.uvs5 = data;
  36024. break;
  36025. case BABYLON.VertexBuffer.UV6Kind:
  36026. this.uvs6 = data;
  36027. break;
  36028. case BABYLON.VertexBuffer.ColorKind:
  36029. this.colors = data;
  36030. break;
  36031. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36032. this.matricesIndices = data;
  36033. break;
  36034. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36035. this.matricesWeights = data;
  36036. break;
  36037. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36038. this.matricesIndicesExtra = data;
  36039. break;
  36040. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36041. this.matricesWeightsExtra = data;
  36042. break;
  36043. }
  36044. };
  36045. /**
  36046. * Associates the vertexData to the passed Mesh.
  36047. * Sets it as updatable or not (default `false`)
  36048. * @param mesh the mesh the vertexData is applied to
  36049. * @param updatable when used and having the value true allows new data to update the vertexData
  36050. * @returns the VertexData
  36051. */
  36052. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36053. this._applyTo(mesh, updatable);
  36054. return this;
  36055. };
  36056. /**
  36057. * Associates the vertexData to the passed Geometry.
  36058. * Sets it as updatable or not (default `false`)
  36059. * @param geometry the geometry the vertexData is applied to
  36060. * @param updatable when used and having the value true allows new data to update the vertexData
  36061. * @returns VertexData
  36062. */
  36063. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36064. this._applyTo(geometry, updatable);
  36065. return this;
  36066. };
  36067. /**
  36068. * Updates the associated mesh
  36069. * @param mesh the mesh to be updated
  36070. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36071. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36072. * @returns VertexData
  36073. */
  36074. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36075. this._update(mesh);
  36076. return this;
  36077. };
  36078. /**
  36079. * Updates the associated geometry
  36080. * @param geometry the geometry to be updated
  36081. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36082. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36083. * @returns VertexData.
  36084. */
  36085. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36086. this._update(geometry);
  36087. return this;
  36088. };
  36089. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36090. if (updatable === void 0) { updatable = false; }
  36091. if (this.positions) {
  36092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36093. }
  36094. if (this.normals) {
  36095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36096. }
  36097. if (this.tangents) {
  36098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36099. }
  36100. if (this.uvs) {
  36101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36102. }
  36103. if (this.uvs2) {
  36104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36105. }
  36106. if (this.uvs3) {
  36107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36108. }
  36109. if (this.uvs4) {
  36110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36111. }
  36112. if (this.uvs5) {
  36113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36114. }
  36115. if (this.uvs6) {
  36116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36117. }
  36118. if (this.colors) {
  36119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36120. }
  36121. if (this.matricesIndices) {
  36122. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36123. }
  36124. if (this.matricesWeights) {
  36125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36126. }
  36127. if (this.matricesIndicesExtra) {
  36128. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36129. }
  36130. if (this.matricesWeightsExtra) {
  36131. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36132. }
  36133. if (this.indices) {
  36134. meshOrGeometry.setIndices(this.indices, null, updatable);
  36135. }
  36136. return this;
  36137. };
  36138. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36139. if (this.positions) {
  36140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36141. }
  36142. if (this.normals) {
  36143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36144. }
  36145. if (this.tangents) {
  36146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36147. }
  36148. if (this.uvs) {
  36149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36150. }
  36151. if (this.uvs2) {
  36152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36153. }
  36154. if (this.uvs3) {
  36155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36156. }
  36157. if (this.uvs4) {
  36158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36159. }
  36160. if (this.uvs5) {
  36161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36162. }
  36163. if (this.uvs6) {
  36164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36165. }
  36166. if (this.colors) {
  36167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36168. }
  36169. if (this.matricesIndices) {
  36170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36171. }
  36172. if (this.matricesWeights) {
  36173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36174. }
  36175. if (this.matricesIndicesExtra) {
  36176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36177. }
  36178. if (this.matricesWeightsExtra) {
  36179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36180. }
  36181. if (this.indices) {
  36182. meshOrGeometry.setIndices(this.indices, null);
  36183. }
  36184. return this;
  36185. };
  36186. /**
  36187. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36188. * @param matrix the transforming matrix
  36189. * @returns the VertexData
  36190. */
  36191. VertexData.prototype.transform = function (matrix) {
  36192. var transformed = BABYLON.Vector3.Zero();
  36193. var index;
  36194. if (this.positions) {
  36195. var position = BABYLON.Vector3.Zero();
  36196. for (index = 0; index < this.positions.length; index += 3) {
  36197. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36198. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36199. this.positions[index] = transformed.x;
  36200. this.positions[index + 1] = transformed.y;
  36201. this.positions[index + 2] = transformed.z;
  36202. }
  36203. }
  36204. if (this.normals) {
  36205. var normal = BABYLON.Vector3.Zero();
  36206. for (index = 0; index < this.normals.length; index += 3) {
  36207. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36208. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36209. this.normals[index] = transformed.x;
  36210. this.normals[index + 1] = transformed.y;
  36211. this.normals[index + 2] = transformed.z;
  36212. }
  36213. }
  36214. if (this.tangents) {
  36215. var tangent = BABYLON.Vector4.Zero();
  36216. var tangentTransformed = BABYLON.Vector4.Zero();
  36217. for (index = 0; index < this.tangents.length; index += 4) {
  36218. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36219. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36220. this.tangents[index] = tangentTransformed.x;
  36221. this.tangents[index + 1] = tangentTransformed.y;
  36222. this.tangents[index + 2] = tangentTransformed.z;
  36223. this.tangents[index + 3] = tangentTransformed.w;
  36224. }
  36225. }
  36226. return this;
  36227. };
  36228. /**
  36229. * Merges the passed VertexData into the current one
  36230. * @param other the VertexData to be merged into the current one
  36231. * @returns the modified VertexData
  36232. */
  36233. VertexData.prototype.merge = function (other) {
  36234. this._validate();
  36235. other._validate();
  36236. if (!this.normals !== !other.normals ||
  36237. !this.tangents !== !other.tangents ||
  36238. !this.uvs !== !other.uvs ||
  36239. !this.uvs2 !== !other.uvs2 ||
  36240. !this.uvs3 !== !other.uvs3 ||
  36241. !this.uvs4 !== !other.uvs4 ||
  36242. !this.uvs5 !== !other.uvs5 ||
  36243. !this.uvs6 !== !other.uvs6 ||
  36244. !this.colors !== !other.colors ||
  36245. !this.matricesIndices !== !other.matricesIndices ||
  36246. !this.matricesWeights !== !other.matricesWeights ||
  36247. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36248. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36249. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36250. }
  36251. if (other.indices) {
  36252. if (!this.indices) {
  36253. this.indices = [];
  36254. }
  36255. var offset = this.positions ? this.positions.length / 3 : 0;
  36256. for (var index = 0; index < other.indices.length; index++) {
  36257. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36258. this.indices.push(other.indices[index] + offset);
  36259. }
  36260. }
  36261. this.positions = this._mergeElement(this.positions, other.positions);
  36262. this.normals = this._mergeElement(this.normals, other.normals);
  36263. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36264. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36265. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36266. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36267. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36268. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36269. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36270. this.colors = this._mergeElement(this.colors, other.colors);
  36271. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36272. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36273. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36274. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36275. return this;
  36276. };
  36277. VertexData.prototype._mergeElement = function (source, other) {
  36278. if (!source) {
  36279. return other;
  36280. }
  36281. if (!other) {
  36282. return source;
  36283. }
  36284. var len = other.length + source.length;
  36285. var isSrcTypedArray = source instanceof Float32Array;
  36286. var isOthTypedArray = other instanceof Float32Array;
  36287. // use non-loop method when the source is Float32Array
  36288. if (isSrcTypedArray) {
  36289. var ret32 = new Float32Array(len);
  36290. ret32.set(source);
  36291. ret32.set(other, source.length);
  36292. return ret32;
  36293. // source is number[], when other is also use concat
  36294. }
  36295. else if (!isOthTypedArray) {
  36296. return source.concat(other);
  36297. // source is a number[], but other is a Float32Array, loop required
  36298. }
  36299. else {
  36300. var ret = source.slice(0); // copy source to a separate array
  36301. for (var i = 0, len = other.length; i < len; i++) {
  36302. ret.push(other[i]);
  36303. }
  36304. return ret;
  36305. }
  36306. };
  36307. VertexData.prototype._validate = function () {
  36308. if (!this.positions) {
  36309. throw new Error("Positions are required");
  36310. }
  36311. var getElementCount = function (kind, values) {
  36312. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36313. if ((values.length % stride) !== 0) {
  36314. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36315. }
  36316. return values.length / stride;
  36317. };
  36318. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36319. var validateElementCount = function (kind, values) {
  36320. var elementCount = getElementCount(kind, values);
  36321. if (elementCount !== positionsElementCount) {
  36322. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36323. }
  36324. };
  36325. if (this.normals)
  36326. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36327. if (this.tangents)
  36328. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36329. if (this.uvs)
  36330. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36331. if (this.uvs2)
  36332. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36333. if (this.uvs3)
  36334. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36335. if (this.uvs4)
  36336. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36337. if (this.uvs5)
  36338. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36339. if (this.uvs6)
  36340. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36341. if (this.colors)
  36342. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36343. if (this.matricesIndices)
  36344. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36345. if (this.matricesWeights)
  36346. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36347. if (this.matricesIndicesExtra)
  36348. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36349. if (this.matricesWeightsExtra)
  36350. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36351. };
  36352. /**
  36353. * Serializes the VertexData
  36354. * @returns a serialized object
  36355. */
  36356. VertexData.prototype.serialize = function () {
  36357. var serializationObject = this.serialize();
  36358. if (this.positions) {
  36359. serializationObject.positions = this.positions;
  36360. }
  36361. if (this.normals) {
  36362. serializationObject.normals = this.normals;
  36363. }
  36364. if (this.tangents) {
  36365. serializationObject.tangents = this.tangents;
  36366. }
  36367. if (this.uvs) {
  36368. serializationObject.uvs = this.uvs;
  36369. }
  36370. if (this.uvs2) {
  36371. serializationObject.uvs2 = this.uvs2;
  36372. }
  36373. if (this.uvs3) {
  36374. serializationObject.uvs3 = this.uvs3;
  36375. }
  36376. if (this.uvs4) {
  36377. serializationObject.uvs4 = this.uvs4;
  36378. }
  36379. if (this.uvs5) {
  36380. serializationObject.uvs5 = this.uvs5;
  36381. }
  36382. if (this.uvs6) {
  36383. serializationObject.uvs6 = this.uvs6;
  36384. }
  36385. if (this.colors) {
  36386. serializationObject.colors = this.colors;
  36387. }
  36388. if (this.matricesIndices) {
  36389. serializationObject.matricesIndices = this.matricesIndices;
  36390. serializationObject.matricesIndices._isExpanded = true;
  36391. }
  36392. if (this.matricesWeights) {
  36393. serializationObject.matricesWeights = this.matricesWeights;
  36394. }
  36395. if (this.matricesIndicesExtra) {
  36396. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36397. serializationObject.matricesIndicesExtra._isExpanded = true;
  36398. }
  36399. if (this.matricesWeightsExtra) {
  36400. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36401. }
  36402. serializationObject.indices = this.indices;
  36403. return serializationObject;
  36404. };
  36405. // Statics
  36406. /**
  36407. * Extracts the vertexData from a mesh
  36408. * @param mesh the mesh from which to extract the VertexData
  36409. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36410. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36411. * @returns the object VertexData associated to the passed mesh
  36412. */
  36413. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36414. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36415. };
  36416. /**
  36417. * Extracts the vertexData from the geometry
  36418. * @param geometry the geometry from which to extract the VertexData
  36419. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36420. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36421. * @returns the object VertexData associated to the passed mesh
  36422. */
  36423. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36424. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36425. };
  36426. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36427. var result = new VertexData();
  36428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36429. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36430. }
  36431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36432. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36433. }
  36434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36435. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36436. }
  36437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36438. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36439. }
  36440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36441. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36442. }
  36443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36444. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36445. }
  36446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36447. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36448. }
  36449. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36450. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36451. }
  36452. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36453. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36454. }
  36455. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36456. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36457. }
  36458. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36459. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36460. }
  36461. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36462. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36463. }
  36464. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36465. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36466. }
  36467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36468. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36469. }
  36470. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36471. return result;
  36472. };
  36473. /**
  36474. * Creates the VertexData for a Ribbon
  36475. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36476. * * pathArray array of paths, each of which an array of successive Vector3
  36477. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36478. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36479. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36480. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36481. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36482. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36483. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36484. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36485. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36486. * @returns the VertexData of the ribbon
  36487. */
  36488. VertexData.CreateRibbon = function (options) {
  36489. var pathArray = options.pathArray;
  36490. var closeArray = options.closeArray || false;
  36491. var closePath = options.closePath || false;
  36492. var invertUV = options.invertUV || false;
  36493. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36494. var offset = options.offset || defaultOffset;
  36495. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36496. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36497. var customUV = options.uvs;
  36498. var customColors = options.colors;
  36499. var positions = [];
  36500. var indices = [];
  36501. var normals = [];
  36502. var uvs = [];
  36503. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36504. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36505. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36506. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36507. var minlg; // minimal length among all paths from pathArray
  36508. var lg = []; // array of path lengths : nb of vertex per path
  36509. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36510. var p; // path iterator
  36511. var i; // point iterator
  36512. var j; // point iterator
  36513. // if single path in pathArray
  36514. if (pathArray.length < 2) {
  36515. var ar1 = [];
  36516. var ar2 = [];
  36517. for (i = 0; i < pathArray[0].length - offset; i++) {
  36518. ar1.push(pathArray[0][i]);
  36519. ar2.push(pathArray[0][i + offset]);
  36520. }
  36521. pathArray = [ar1, ar2];
  36522. }
  36523. // positions and horizontal distances (u)
  36524. var idc = 0;
  36525. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36526. var path;
  36527. var l;
  36528. minlg = pathArray[0].length;
  36529. var vectlg;
  36530. var dist;
  36531. for (p = 0; p < pathArray.length; p++) {
  36532. uTotalDistance[p] = 0;
  36533. us[p] = [0];
  36534. path = pathArray[p];
  36535. l = path.length;
  36536. minlg = (minlg < l) ? minlg : l;
  36537. j = 0;
  36538. while (j < l) {
  36539. positions.push(path[j].x, path[j].y, path[j].z);
  36540. if (j > 0) {
  36541. vectlg = path[j].subtract(path[j - 1]).length();
  36542. dist = vectlg + uTotalDistance[p];
  36543. us[p].push(dist);
  36544. uTotalDistance[p] = dist;
  36545. }
  36546. j++;
  36547. }
  36548. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36549. j--;
  36550. positions.push(path[0].x, path[0].y, path[0].z);
  36551. vectlg = path[j].subtract(path[0]).length();
  36552. dist = vectlg + uTotalDistance[p];
  36553. us[p].push(dist);
  36554. uTotalDistance[p] = dist;
  36555. }
  36556. lg[p] = l + closePathCorr;
  36557. idx[p] = idc;
  36558. idc += (l + closePathCorr);
  36559. }
  36560. // vertical distances (v)
  36561. var path1;
  36562. var path2;
  36563. var vertex1 = null;
  36564. var vertex2 = null;
  36565. for (i = 0; i < minlg + closePathCorr; i++) {
  36566. vTotalDistance[i] = 0;
  36567. vs[i] = [0];
  36568. for (p = 0; p < pathArray.length - 1; p++) {
  36569. path1 = pathArray[p];
  36570. path2 = pathArray[p + 1];
  36571. if (i === minlg) { // closePath
  36572. vertex1 = path1[0];
  36573. vertex2 = path2[0];
  36574. }
  36575. else {
  36576. vertex1 = path1[i];
  36577. vertex2 = path2[i];
  36578. }
  36579. vectlg = vertex2.subtract(vertex1).length();
  36580. dist = vectlg + vTotalDistance[i];
  36581. vs[i].push(dist);
  36582. vTotalDistance[i] = dist;
  36583. }
  36584. if (closeArray && vertex2 && vertex1) {
  36585. path1 = pathArray[p];
  36586. path2 = pathArray[0];
  36587. if (i === minlg) { // closePath
  36588. vertex2 = path2[0];
  36589. }
  36590. vectlg = vertex2.subtract(vertex1).length();
  36591. dist = vectlg + vTotalDistance[i];
  36592. vTotalDistance[i] = dist;
  36593. }
  36594. }
  36595. // uvs
  36596. var u;
  36597. var v;
  36598. if (customUV) {
  36599. for (p = 0; p < customUV.length; p++) {
  36600. uvs.push(customUV[p].x, customUV[p].y);
  36601. }
  36602. }
  36603. else {
  36604. for (p = 0; p < pathArray.length; p++) {
  36605. for (i = 0; i < minlg + closePathCorr; i++) {
  36606. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36607. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36608. if (invertUV) {
  36609. uvs.push(v, u);
  36610. }
  36611. else {
  36612. uvs.push(u, v);
  36613. }
  36614. }
  36615. }
  36616. }
  36617. // indices
  36618. p = 0; // path index
  36619. var pi = 0; // positions array index
  36620. var l1 = lg[p] - 1; // path1 length
  36621. var l2 = lg[p + 1] - 1; // path2 length
  36622. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36623. var shft = idx[1] - idx[0]; // shift
  36624. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36625. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36626. // 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
  36627. indices.push(pi, pi + shft, pi + 1);
  36628. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36629. pi += 1;
  36630. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36631. p++;
  36632. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36633. shft = idx[0] - idx[p];
  36634. l1 = lg[p] - 1;
  36635. l2 = lg[0] - 1;
  36636. }
  36637. else {
  36638. shft = idx[p + 1] - idx[p];
  36639. l1 = lg[p] - 1;
  36640. l2 = lg[p + 1] - 1;
  36641. }
  36642. pi = idx[p];
  36643. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36644. }
  36645. }
  36646. // normals
  36647. VertexData.ComputeNormals(positions, indices, normals);
  36648. if (closePath) { // update both the first and last vertex normals to their average value
  36649. var indexFirst = 0;
  36650. var indexLast = 0;
  36651. for (p = 0; p < pathArray.length; p++) {
  36652. indexFirst = idx[p] * 3;
  36653. if (p + 1 < pathArray.length) {
  36654. indexLast = (idx[p + 1] - 1) * 3;
  36655. }
  36656. else {
  36657. indexLast = normals.length - 3;
  36658. }
  36659. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36660. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36661. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36662. normals[indexLast] = normals[indexFirst];
  36663. normals[indexLast + 1] = normals[indexFirst + 1];
  36664. normals[indexLast + 2] = normals[indexFirst + 2];
  36665. }
  36666. }
  36667. // sides
  36668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36669. // Colors
  36670. var colors = null;
  36671. if (customColors) {
  36672. colors = new Float32Array(customColors.length * 4);
  36673. for (var c = 0; c < customColors.length; c++) {
  36674. colors[c * 4] = customColors[c].r;
  36675. colors[c * 4 + 1] = customColors[c].g;
  36676. colors[c * 4 + 2] = customColors[c].b;
  36677. colors[c * 4 + 3] = customColors[c].a;
  36678. }
  36679. }
  36680. // Result
  36681. var vertexData = new VertexData();
  36682. var positions32 = new Float32Array(positions);
  36683. var normals32 = new Float32Array(normals);
  36684. var uvs32 = new Float32Array(uvs);
  36685. vertexData.indices = indices;
  36686. vertexData.positions = positions32;
  36687. vertexData.normals = normals32;
  36688. vertexData.uvs = uvs32;
  36689. if (colors) {
  36690. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36691. }
  36692. if (closePath) {
  36693. vertexData._idx = idx;
  36694. }
  36695. return vertexData;
  36696. };
  36697. /**
  36698. * Creates the VertexData for a box
  36699. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36700. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36701. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36702. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36703. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36704. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36705. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36706. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36707. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36708. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36709. * @returns the VertexData of the box
  36710. */
  36711. VertexData.CreateBox = function (options) {
  36712. var normalsSource = [
  36713. new BABYLON.Vector3(0, 0, 1),
  36714. new BABYLON.Vector3(0, 0, -1),
  36715. new BABYLON.Vector3(1, 0, 0),
  36716. new BABYLON.Vector3(-1, 0, 0),
  36717. new BABYLON.Vector3(0, 1, 0),
  36718. new BABYLON.Vector3(0, -1, 0)
  36719. ];
  36720. var indices = [];
  36721. var positions = [];
  36722. var normals = [];
  36723. var uvs = [];
  36724. var width = options.width || options.size || 1;
  36725. var height = options.height || options.size || 1;
  36726. var depth = options.depth || options.size || 1;
  36727. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36728. var faceUV = options.faceUV || new Array(6);
  36729. var faceColors = options.faceColors;
  36730. var colors = [];
  36731. // default face colors and UV if undefined
  36732. for (var f = 0; f < 6; f++) {
  36733. if (faceUV[f] === undefined) {
  36734. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36735. }
  36736. if (faceColors && faceColors[f] === undefined) {
  36737. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36738. }
  36739. }
  36740. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36741. // Create each face in turn.
  36742. for (var index = 0; index < normalsSource.length; index++) {
  36743. var normal = normalsSource[index];
  36744. // Get two vectors perpendicular to the face normal and to each other.
  36745. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36746. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36747. // Six indices (two triangles) per face.
  36748. var verticesLength = positions.length / 3;
  36749. indices.push(verticesLength);
  36750. indices.push(verticesLength + 1);
  36751. indices.push(verticesLength + 2);
  36752. indices.push(verticesLength);
  36753. indices.push(verticesLength + 2);
  36754. indices.push(verticesLength + 3);
  36755. // Four vertices per face.
  36756. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36757. positions.push(vertex.x, vertex.y, vertex.z);
  36758. normals.push(normal.x, normal.y, normal.z);
  36759. uvs.push(faceUV[index].z, faceUV[index].w);
  36760. if (faceColors) {
  36761. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36762. }
  36763. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36764. positions.push(vertex.x, vertex.y, vertex.z);
  36765. normals.push(normal.x, normal.y, normal.z);
  36766. uvs.push(faceUV[index].x, faceUV[index].w);
  36767. if (faceColors) {
  36768. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36769. }
  36770. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36771. positions.push(vertex.x, vertex.y, vertex.z);
  36772. normals.push(normal.x, normal.y, normal.z);
  36773. uvs.push(faceUV[index].x, faceUV[index].y);
  36774. if (faceColors) {
  36775. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36776. }
  36777. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36778. positions.push(vertex.x, vertex.y, vertex.z);
  36779. normals.push(normal.x, normal.y, normal.z);
  36780. uvs.push(faceUV[index].z, faceUV[index].y);
  36781. if (faceColors) {
  36782. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36783. }
  36784. }
  36785. // sides
  36786. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36787. // Result
  36788. var vertexData = new VertexData();
  36789. vertexData.indices = indices;
  36790. vertexData.positions = positions;
  36791. vertexData.normals = normals;
  36792. vertexData.uvs = uvs;
  36793. if (faceColors) {
  36794. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36795. vertexData.colors = totalColors;
  36796. }
  36797. return vertexData;
  36798. };
  36799. /**
  36800. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36801. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36802. * * segments sets the number of horizontal strips optional, default 32
  36803. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36804. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36805. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36806. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36807. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36808. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36809. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36810. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36811. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36812. * @returns the VertexData of the ellipsoid
  36813. */
  36814. VertexData.CreateSphere = function (options) {
  36815. var segments = options.segments || 32;
  36816. var diameterX = options.diameterX || options.diameter || 1;
  36817. var diameterY = options.diameterY || options.diameter || 1;
  36818. var diameterZ = options.diameterZ || options.diameter || 1;
  36819. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36820. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36821. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36822. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36823. var totalZRotationSteps = 2 + segments;
  36824. var totalYRotationSteps = 2 * totalZRotationSteps;
  36825. var indices = [];
  36826. var positions = [];
  36827. var normals = [];
  36828. var uvs = [];
  36829. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36830. var normalizedZ = zRotationStep / totalZRotationSteps;
  36831. var angleZ = normalizedZ * Math.PI * slice;
  36832. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36833. var normalizedY = yRotationStep / totalYRotationSteps;
  36834. var angleY = normalizedY * Math.PI * 2 * arc;
  36835. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36836. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36837. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36838. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36839. var vertex = complete.multiply(radius);
  36840. var normal = complete.divide(radius).normalize();
  36841. positions.push(vertex.x, vertex.y, vertex.z);
  36842. normals.push(normal.x, normal.y, normal.z);
  36843. uvs.push(normalizedY, normalizedZ);
  36844. }
  36845. if (zRotationStep > 0) {
  36846. var verticesCount = positions.length / 3;
  36847. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36848. indices.push((firstIndex));
  36849. indices.push((firstIndex + 1));
  36850. indices.push(firstIndex + totalYRotationSteps + 1);
  36851. indices.push((firstIndex + totalYRotationSteps + 1));
  36852. indices.push((firstIndex + 1));
  36853. indices.push((firstIndex + totalYRotationSteps + 2));
  36854. }
  36855. }
  36856. }
  36857. // Sides
  36858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36859. // Result
  36860. var vertexData = new VertexData();
  36861. vertexData.indices = indices;
  36862. vertexData.positions = positions;
  36863. vertexData.normals = normals;
  36864. vertexData.uvs = uvs;
  36865. return vertexData;
  36866. };
  36867. /**
  36868. * Creates the VertexData for a cylinder, cone or prism
  36869. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36870. * * height sets the height (y direction) of the cylinder, optional, default 2
  36871. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36872. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36873. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36874. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36875. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36876. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36877. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36878. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36879. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36880. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36881. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36882. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36883. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36884. * @returns the VertexData of the cylinder, cone or prism
  36885. */
  36886. VertexData.CreateCylinder = function (options) {
  36887. var height = options.height || 2;
  36888. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36889. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36890. var tessellation = options.tessellation || 24;
  36891. var subdivisions = options.subdivisions || 1;
  36892. var hasRings = options.hasRings ? true : false;
  36893. var enclose = options.enclose ? true : false;
  36894. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36895. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36896. var faceUV = options.faceUV || new Array(3);
  36897. var faceColors = options.faceColors;
  36898. // default face colors and UV if undefined
  36899. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36900. var ringNb = (hasRings) ? subdivisions : 1;
  36901. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36902. var f;
  36903. for (f = 0; f < surfaceNb; f++) {
  36904. if (faceColors && faceColors[f] === undefined) {
  36905. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36906. }
  36907. }
  36908. for (f = 0; f < surfaceNb; f++) {
  36909. if (faceUV && faceUV[f] === undefined) {
  36910. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36911. }
  36912. }
  36913. var indices = new Array();
  36914. var positions = new Array();
  36915. var normals = new Array();
  36916. var uvs = new Array();
  36917. var colors = new Array();
  36918. var angle_step = Math.PI * 2 * arc / tessellation;
  36919. var angle;
  36920. var h;
  36921. var radius;
  36922. var tan = (diameterBottom - diameterTop) / 2 / height;
  36923. var ringVertex = BABYLON.Vector3.Zero();
  36924. var ringNormal = BABYLON.Vector3.Zero();
  36925. var ringFirstVertex = BABYLON.Vector3.Zero();
  36926. var ringFirstNormal = BABYLON.Vector3.Zero();
  36927. var quadNormal = BABYLON.Vector3.Zero();
  36928. var Y = BABYLON.Axis.Y;
  36929. // positions, normals, uvs
  36930. var i;
  36931. var j;
  36932. var r;
  36933. var ringIdx = 1;
  36934. var s = 1; // surface index
  36935. var cs = 0;
  36936. var v = 0;
  36937. for (i = 0; i <= subdivisions; i++) {
  36938. h = i / subdivisions;
  36939. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36940. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36941. for (r = 0; r < ringIdx; r++) {
  36942. if (hasRings) {
  36943. s += r;
  36944. }
  36945. if (enclose) {
  36946. s += 2 * r;
  36947. }
  36948. for (j = 0; j <= tessellation; j++) {
  36949. angle = j * angle_step;
  36950. // position
  36951. ringVertex.x = Math.cos(-angle) * radius;
  36952. ringVertex.y = -height / 2 + h * height;
  36953. ringVertex.z = Math.sin(-angle) * radius;
  36954. // normal
  36955. if (diameterTop === 0 && i === subdivisions) {
  36956. // if no top cap, reuse former normals
  36957. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36958. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36959. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36960. }
  36961. else {
  36962. ringNormal.x = ringVertex.x;
  36963. ringNormal.z = ringVertex.z;
  36964. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36965. ringNormal.normalize();
  36966. }
  36967. // keep first ring vertex values for enclose
  36968. if (j === 0) {
  36969. ringFirstVertex.copyFrom(ringVertex);
  36970. ringFirstNormal.copyFrom(ringNormal);
  36971. }
  36972. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36973. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36974. if (hasRings) {
  36975. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36976. }
  36977. else {
  36978. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36979. }
  36980. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36981. if (faceColors) {
  36982. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36983. }
  36984. }
  36985. // if enclose, add four vertices and their dedicated normals
  36986. if (arc !== 1 && enclose) {
  36987. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36988. positions.push(0, ringVertex.y, 0);
  36989. positions.push(0, ringVertex.y, 0);
  36990. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36991. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36992. quadNormal.normalize();
  36993. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36994. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36995. quadNormal.normalize();
  36996. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36997. if (hasRings) {
  36998. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36999. }
  37000. else {
  37001. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37002. }
  37003. uvs.push(faceUV[s + 1].x, v);
  37004. uvs.push(faceUV[s + 1].z, v);
  37005. if (hasRings) {
  37006. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37007. }
  37008. else {
  37009. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37010. }
  37011. uvs.push(faceUV[s + 2].x, v);
  37012. uvs.push(faceUV[s + 2].z, v);
  37013. if (faceColors) {
  37014. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37015. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37016. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37017. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37018. }
  37019. }
  37020. if (cs !== s) {
  37021. cs = s;
  37022. }
  37023. }
  37024. }
  37025. // indices
  37026. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37027. var s;
  37028. i = 0;
  37029. for (s = 0; s < subdivisions; s++) {
  37030. var i0 = 0;
  37031. var i1 = 0;
  37032. var i2 = 0;
  37033. var i3 = 0;
  37034. for (j = 0; j < tessellation; j++) {
  37035. i0 = i * (e + 1) + j;
  37036. i1 = (i + 1) * (e + 1) + j;
  37037. i2 = i * (e + 1) + (j + 1);
  37038. i3 = (i + 1) * (e + 1) + (j + 1);
  37039. indices.push(i0, i1, i2);
  37040. indices.push(i3, i2, i1);
  37041. }
  37042. if (arc !== 1 && enclose) { // if enclose, add two quads
  37043. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37044. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37045. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37046. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37047. }
  37048. i = (hasRings) ? (i + 2) : (i + 1);
  37049. }
  37050. // Caps
  37051. var createCylinderCap = function (isTop) {
  37052. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37053. if (radius === 0) {
  37054. return;
  37055. }
  37056. // Cap positions, normals & uvs
  37057. var angle;
  37058. var circleVector;
  37059. var i;
  37060. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37061. var c = null;
  37062. if (faceColors) {
  37063. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37064. }
  37065. // cap center
  37066. var vbase = positions.length / 3;
  37067. var offset = isTop ? height / 2 : -height / 2;
  37068. var center = new BABYLON.Vector3(0, offset, 0);
  37069. positions.push(center.x, center.y, center.z);
  37070. normals.push(0, isTop ? 1 : -1, 0);
  37071. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37072. if (c) {
  37073. colors.push(c.r, c.g, c.b, c.a);
  37074. }
  37075. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37076. for (i = 0; i <= tessellation; i++) {
  37077. angle = Math.PI * 2 * i * arc / tessellation;
  37078. var cos = Math.cos(-angle);
  37079. var sin = Math.sin(-angle);
  37080. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37081. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37082. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37083. normals.push(0, isTop ? 1 : -1, 0);
  37084. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37085. if (c) {
  37086. colors.push(c.r, c.g, c.b, c.a);
  37087. }
  37088. }
  37089. // Cap indices
  37090. for (i = 0; i < tessellation; i++) {
  37091. if (!isTop) {
  37092. indices.push(vbase);
  37093. indices.push(vbase + (i + 1));
  37094. indices.push(vbase + (i + 2));
  37095. }
  37096. else {
  37097. indices.push(vbase);
  37098. indices.push(vbase + (i + 2));
  37099. indices.push(vbase + (i + 1));
  37100. }
  37101. }
  37102. };
  37103. // add caps to geometry
  37104. createCylinderCap(false);
  37105. createCylinderCap(true);
  37106. // Sides
  37107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37108. var vertexData = new VertexData();
  37109. vertexData.indices = indices;
  37110. vertexData.positions = positions;
  37111. vertexData.normals = normals;
  37112. vertexData.uvs = uvs;
  37113. if (faceColors) {
  37114. vertexData.colors = colors;
  37115. }
  37116. return vertexData;
  37117. };
  37118. /**
  37119. * Creates the VertexData for a torus
  37120. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37121. * * diameter the diameter of the torus, optional default 1
  37122. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37123. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37124. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37125. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37126. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37127. * @returns the VertexData of the torus
  37128. */
  37129. VertexData.CreateTorus = function (options) {
  37130. var indices = [];
  37131. var positions = [];
  37132. var normals = [];
  37133. var uvs = [];
  37134. var diameter = options.diameter || 1;
  37135. var thickness = options.thickness || 0.5;
  37136. var tessellation = options.tessellation || 16;
  37137. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37138. var stride = tessellation + 1;
  37139. for (var i = 0; i <= tessellation; i++) {
  37140. var u = i / tessellation;
  37141. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37142. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37143. for (var j = 0; j <= tessellation; j++) {
  37144. var v = 1 - j / tessellation;
  37145. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37146. var dx = Math.cos(innerAngle);
  37147. var dy = Math.sin(innerAngle);
  37148. // Create a vertex.
  37149. var normal = new BABYLON.Vector3(dx, dy, 0);
  37150. var position = normal.scale(thickness / 2);
  37151. var textureCoordinate = new BABYLON.Vector2(u, v);
  37152. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37153. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37154. positions.push(position.x, position.y, position.z);
  37155. normals.push(normal.x, normal.y, normal.z);
  37156. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37157. // And create indices for two triangles.
  37158. var nextI = (i + 1) % stride;
  37159. var nextJ = (j + 1) % stride;
  37160. indices.push(i * stride + j);
  37161. indices.push(i * stride + nextJ);
  37162. indices.push(nextI * stride + j);
  37163. indices.push(i * stride + nextJ);
  37164. indices.push(nextI * stride + nextJ);
  37165. indices.push(nextI * stride + j);
  37166. }
  37167. }
  37168. // Sides
  37169. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37170. // Result
  37171. var vertexData = new VertexData();
  37172. vertexData.indices = indices;
  37173. vertexData.positions = positions;
  37174. vertexData.normals = normals;
  37175. vertexData.uvs = uvs;
  37176. return vertexData;
  37177. };
  37178. /**
  37179. * Creates the VertexData of the LineSystem
  37180. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37181. * - lines an array of lines, each line being an array of successive Vector3
  37182. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37183. * @returns the VertexData of the LineSystem
  37184. */
  37185. VertexData.CreateLineSystem = function (options) {
  37186. var indices = [];
  37187. var positions = [];
  37188. var lines = options.lines;
  37189. var colors = options.colors;
  37190. var vertexColors = [];
  37191. var idx = 0;
  37192. for (var l = 0; l < lines.length; l++) {
  37193. var points = lines[l];
  37194. for (var index = 0; index < points.length; index++) {
  37195. positions.push(points[index].x, points[index].y, points[index].z);
  37196. if (colors) {
  37197. var color = colors[l];
  37198. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37199. }
  37200. if (index > 0) {
  37201. indices.push(idx - 1);
  37202. indices.push(idx);
  37203. }
  37204. idx++;
  37205. }
  37206. }
  37207. var vertexData = new VertexData();
  37208. vertexData.indices = indices;
  37209. vertexData.positions = positions;
  37210. if (colors) {
  37211. vertexData.colors = vertexColors;
  37212. }
  37213. return vertexData;
  37214. };
  37215. /**
  37216. * Create the VertexData for a DashedLines
  37217. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37218. * - points an array successive Vector3
  37219. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37220. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37221. * - dashNb the intended total number of dashes, optional, default 200
  37222. * @returns the VertexData for the DashedLines
  37223. */
  37224. VertexData.CreateDashedLines = function (options) {
  37225. var dashSize = options.dashSize || 3;
  37226. var gapSize = options.gapSize || 1;
  37227. var dashNb = options.dashNb || 200;
  37228. var points = options.points;
  37229. var positions = new Array();
  37230. var indices = new Array();
  37231. var curvect = BABYLON.Vector3.Zero();
  37232. var lg = 0;
  37233. var nb = 0;
  37234. var shft = 0;
  37235. var dashshft = 0;
  37236. var curshft = 0;
  37237. var idx = 0;
  37238. var i = 0;
  37239. for (i = 0; i < points.length - 1; i++) {
  37240. points[i + 1].subtractToRef(points[i], curvect);
  37241. lg += curvect.length();
  37242. }
  37243. shft = lg / dashNb;
  37244. dashshft = dashSize * shft / (dashSize + gapSize);
  37245. for (i = 0; i < points.length - 1; i++) {
  37246. points[i + 1].subtractToRef(points[i], curvect);
  37247. nb = Math.floor(curvect.length() / shft);
  37248. curvect.normalize();
  37249. for (var j = 0; j < nb; j++) {
  37250. curshft = shft * j;
  37251. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37252. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37253. indices.push(idx, idx + 1);
  37254. idx += 2;
  37255. }
  37256. }
  37257. // Result
  37258. var vertexData = new VertexData();
  37259. vertexData.positions = positions;
  37260. vertexData.indices = indices;
  37261. return vertexData;
  37262. };
  37263. /**
  37264. * Creates the VertexData for a Ground
  37265. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37266. * - width the width (x direction) of the ground, optional, default 1
  37267. * - height the height (z direction) of the ground, optional, default 1
  37268. * - subdivisions the number of subdivisions per side, optional, default 1
  37269. * @returns the VertexData of the Ground
  37270. */
  37271. VertexData.CreateGround = function (options) {
  37272. var indices = [];
  37273. var positions = [];
  37274. var normals = [];
  37275. var uvs = [];
  37276. var row, col;
  37277. var width = options.width || 1;
  37278. var height = options.height || 1;
  37279. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37280. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37281. for (row = 0; row <= subdivisionsY; row++) {
  37282. for (col = 0; col <= subdivisionsX; col++) {
  37283. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37284. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37285. positions.push(position.x, position.y, position.z);
  37286. normals.push(normal.x, normal.y, normal.z);
  37287. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37288. }
  37289. }
  37290. for (row = 0; row < subdivisionsY; row++) {
  37291. for (col = 0; col < subdivisionsX; col++) {
  37292. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37293. indices.push(col + 1 + row * (subdivisionsX + 1));
  37294. indices.push(col + row * (subdivisionsX + 1));
  37295. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37296. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37297. indices.push(col + row * (subdivisionsX + 1));
  37298. }
  37299. }
  37300. // Result
  37301. var vertexData = new VertexData();
  37302. vertexData.indices = indices;
  37303. vertexData.positions = positions;
  37304. vertexData.normals = normals;
  37305. vertexData.uvs = uvs;
  37306. return vertexData;
  37307. };
  37308. /**
  37309. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37310. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37311. * * xmin the ground minimum X coordinate, optional, default -1
  37312. * * zmin the ground minimum Z coordinate, optional, default -1
  37313. * * xmax the ground maximum X coordinate, optional, default 1
  37314. * * zmax the ground maximum Z coordinate, optional, default 1
  37315. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37316. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37317. * @returns the VertexData of the TiledGround
  37318. */
  37319. VertexData.CreateTiledGround = function (options) {
  37320. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37321. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37322. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37323. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37324. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37325. var precision = options.precision || { w: 1, h: 1 };
  37326. var indices = new Array();
  37327. var positions = new Array();
  37328. var normals = new Array();
  37329. var uvs = new Array();
  37330. var row, col, tileRow, tileCol;
  37331. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37332. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37333. precision.w = (precision.w < 1) ? 1 : precision.w;
  37334. precision.h = (precision.h < 1) ? 1 : precision.h;
  37335. var tileSize = {
  37336. 'w': (xmax - xmin) / subdivisions.w,
  37337. 'h': (zmax - zmin) / subdivisions.h
  37338. };
  37339. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37340. // Indices
  37341. var base = positions.length / 3;
  37342. var rowLength = precision.w + 1;
  37343. for (row = 0; row < precision.h; row++) {
  37344. for (col = 0; col < precision.w; col++) {
  37345. var square = [
  37346. base + col + row * rowLength,
  37347. base + (col + 1) + row * rowLength,
  37348. base + (col + 1) + (row + 1) * rowLength,
  37349. base + col + (row + 1) * rowLength
  37350. ];
  37351. indices.push(square[1]);
  37352. indices.push(square[2]);
  37353. indices.push(square[3]);
  37354. indices.push(square[0]);
  37355. indices.push(square[1]);
  37356. indices.push(square[3]);
  37357. }
  37358. }
  37359. // Position, normals and uvs
  37360. var position = BABYLON.Vector3.Zero();
  37361. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37362. for (row = 0; row <= precision.h; row++) {
  37363. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37364. for (col = 0; col <= precision.w; col++) {
  37365. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37366. position.y = 0;
  37367. positions.push(position.x, position.y, position.z);
  37368. normals.push(normal.x, normal.y, normal.z);
  37369. uvs.push(col / precision.w, row / precision.h);
  37370. }
  37371. }
  37372. }
  37373. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37374. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37375. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37376. }
  37377. }
  37378. // Result
  37379. var vertexData = new VertexData();
  37380. vertexData.indices = indices;
  37381. vertexData.positions = positions;
  37382. vertexData.normals = normals;
  37383. vertexData.uvs = uvs;
  37384. return vertexData;
  37385. };
  37386. /**
  37387. * Creates the VertexData of the Ground designed from a heightmap
  37388. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37389. * * width the width (x direction) of the ground
  37390. * * height the height (z direction) of the ground
  37391. * * subdivisions the number of subdivisions per side
  37392. * * minHeight the minimum altitude on the ground, optional, default 0
  37393. * * maxHeight the maximum altitude on the ground, optional default 1
  37394. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37395. * * buffer the array holding the image color data
  37396. * * bufferWidth the width of image
  37397. * * bufferHeight the height of image
  37398. * @returns the VertexData of the Ground designed from a heightmap
  37399. */
  37400. VertexData.CreateGroundFromHeightMap = function (options) {
  37401. var indices = [];
  37402. var positions = [];
  37403. var normals = [];
  37404. var uvs = [];
  37405. var row, col;
  37406. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37407. // Vertices
  37408. for (row = 0; row <= options.subdivisions; row++) {
  37409. for (col = 0; col <= options.subdivisions; col++) {
  37410. 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));
  37411. // Compute height
  37412. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37413. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37414. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37415. var r = options.buffer[pos] / 255.0;
  37416. var g = options.buffer[pos + 1] / 255.0;
  37417. var b = options.buffer[pos + 2] / 255.0;
  37418. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37419. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37420. // Add vertex
  37421. positions.push(position.x, position.y, position.z);
  37422. normals.push(0, 0, 0);
  37423. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37424. }
  37425. }
  37426. // Indices
  37427. for (row = 0; row < options.subdivisions; row++) {
  37428. for (col = 0; col < options.subdivisions; col++) {
  37429. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37430. indices.push(col + 1 + row * (options.subdivisions + 1));
  37431. indices.push(col + row * (options.subdivisions + 1));
  37432. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37433. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37434. indices.push(col + row * (options.subdivisions + 1));
  37435. }
  37436. }
  37437. // Normals
  37438. VertexData.ComputeNormals(positions, indices, normals);
  37439. // Result
  37440. var vertexData = new VertexData();
  37441. vertexData.indices = indices;
  37442. vertexData.positions = positions;
  37443. vertexData.normals = normals;
  37444. vertexData.uvs = uvs;
  37445. return vertexData;
  37446. };
  37447. /**
  37448. * Creates the VertexData for a Plane
  37449. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37450. * * size sets the width and height of the plane to the value of size, optional default 1
  37451. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37452. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37453. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37454. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37455. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37456. * @returns the VertexData of the box
  37457. */
  37458. VertexData.CreatePlane = function (options) {
  37459. var indices = [];
  37460. var positions = [];
  37461. var normals = [];
  37462. var uvs = [];
  37463. var width = options.width || options.size || 1;
  37464. var height = options.height || options.size || 1;
  37465. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37466. // Vertices
  37467. var halfWidth = width / 2.0;
  37468. var halfHeight = height / 2.0;
  37469. positions.push(-halfWidth, -halfHeight, 0);
  37470. normals.push(0, 0, -1.0);
  37471. uvs.push(0.0, 0.0);
  37472. positions.push(halfWidth, -halfHeight, 0);
  37473. normals.push(0, 0, -1.0);
  37474. uvs.push(1.0, 0.0);
  37475. positions.push(halfWidth, halfHeight, 0);
  37476. normals.push(0, 0, -1.0);
  37477. uvs.push(1.0, 1.0);
  37478. positions.push(-halfWidth, halfHeight, 0);
  37479. normals.push(0, 0, -1.0);
  37480. uvs.push(0.0, 1.0);
  37481. // Indices
  37482. indices.push(0);
  37483. indices.push(1);
  37484. indices.push(2);
  37485. indices.push(0);
  37486. indices.push(2);
  37487. indices.push(3);
  37488. // Sides
  37489. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37490. // Result
  37491. var vertexData = new VertexData();
  37492. vertexData.indices = indices;
  37493. vertexData.positions = positions;
  37494. vertexData.normals = normals;
  37495. vertexData.uvs = uvs;
  37496. return vertexData;
  37497. };
  37498. /**
  37499. * Creates the VertexData of the Disc or regular Polygon
  37500. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37501. * * radius the radius of the disc, optional default 0.5
  37502. * * tessellation the number of polygon sides, optional, default 64
  37503. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37504. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37505. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37506. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37507. * @returns the VertexData of the box
  37508. */
  37509. VertexData.CreateDisc = function (options) {
  37510. var positions = new Array();
  37511. var indices = new Array();
  37512. var normals = new Array();
  37513. var uvs = new Array();
  37514. var radius = options.radius || 0.5;
  37515. var tessellation = options.tessellation || 64;
  37516. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37517. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37518. // positions and uvs
  37519. positions.push(0, 0, 0); // disc center first
  37520. uvs.push(0.5, 0.5);
  37521. var theta = Math.PI * 2 * arc;
  37522. var step = theta / tessellation;
  37523. for (var a = 0; a < theta; a += step) {
  37524. var x = Math.cos(a);
  37525. var y = Math.sin(a);
  37526. var u = (x + 1) / 2;
  37527. var v = (1 - y) / 2;
  37528. positions.push(radius * x, radius * y, 0);
  37529. uvs.push(u, v);
  37530. }
  37531. if (arc === 1) {
  37532. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37533. uvs.push(uvs[2], uvs[3]);
  37534. }
  37535. //indices
  37536. var vertexNb = positions.length / 3;
  37537. for (var i = 1; i < vertexNb - 1; i++) {
  37538. indices.push(i + 1, 0, i);
  37539. }
  37540. // result
  37541. VertexData.ComputeNormals(positions, indices, normals);
  37542. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37543. var vertexData = new VertexData();
  37544. vertexData.indices = indices;
  37545. vertexData.positions = positions;
  37546. vertexData.normals = normals;
  37547. vertexData.uvs = uvs;
  37548. return vertexData;
  37549. };
  37550. /**
  37551. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37552. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37553. * @param polygon a mesh built from polygonTriangulation.build()
  37554. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37555. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37556. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37557. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37558. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37559. * @returns the VertexData of the Polygon
  37560. */
  37561. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37562. var faceUV = fUV || new Array(3);
  37563. var faceColors = fColors;
  37564. var colors = [];
  37565. // default face colors and UV if undefined
  37566. for (var f = 0; f < 3; f++) {
  37567. if (faceUV[f] === undefined) {
  37568. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37569. }
  37570. if (faceColors && faceColors[f] === undefined) {
  37571. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37572. }
  37573. }
  37574. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37575. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37576. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37577. var indices = polygon.getIndices();
  37578. // set face colours and textures
  37579. var idx = 0;
  37580. var face = 0;
  37581. for (var index = 0; index < normals.length; index += 3) {
  37582. //Edge Face no. 1
  37583. if (Math.abs(normals[index + 1]) < 0.001) {
  37584. face = 1;
  37585. }
  37586. //Top Face no. 0
  37587. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37588. face = 0;
  37589. }
  37590. //Bottom Face no. 2
  37591. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37592. face = 2;
  37593. }
  37594. idx = index / 3;
  37595. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37596. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37597. if (faceColors) {
  37598. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37599. }
  37600. }
  37601. // sides
  37602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37603. // Result
  37604. var vertexData = new VertexData();
  37605. vertexData.indices = indices;
  37606. vertexData.positions = positions;
  37607. vertexData.normals = normals;
  37608. vertexData.uvs = uvs;
  37609. if (faceColors) {
  37610. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37611. vertexData.colors = totalColors;
  37612. }
  37613. return vertexData;
  37614. };
  37615. /**
  37616. * Creates the VertexData of the IcoSphere
  37617. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37618. * * radius the radius of the IcoSphere, optional default 1
  37619. * * radiusX allows stretching in the x direction, optional, default radius
  37620. * * radiusY allows stretching in the y direction, optional, default radius
  37621. * * radiusZ allows stretching in the z direction, optional, default radius
  37622. * * flat when true creates a flat shaded mesh, optional, default true
  37623. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37624. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37625. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37626. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37627. * @returns the VertexData of the IcoSphere
  37628. */
  37629. VertexData.CreateIcoSphere = function (options) {
  37630. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37631. var radius = options.radius || 1;
  37632. var flat = (options.flat === undefined) ? true : options.flat;
  37633. var subdivisions = options.subdivisions || 4;
  37634. var radiusX = options.radiusX || radius;
  37635. var radiusY = options.radiusY || radius;
  37636. var radiusZ = options.radiusZ || radius;
  37637. var t = (1 + Math.sqrt(5)) / 2;
  37638. // 12 vertex x,y,z
  37639. var ico_vertices = [
  37640. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37641. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37642. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37643. ];
  37644. // index of 3 vertex makes a face of icopshere
  37645. var ico_indices = [
  37646. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37647. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37648. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37649. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37650. ];
  37651. // vertex for uv have aliased position, not for UV
  37652. var vertices_unalias_id = [
  37653. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37654. // vertex alias
  37655. 0,
  37656. 2,
  37657. 3,
  37658. 3,
  37659. 3,
  37660. 4,
  37661. 7,
  37662. 8,
  37663. 9,
  37664. 9,
  37665. 10,
  37666. 11 // 23: B + 12
  37667. ];
  37668. // uv as integer step (not pixels !)
  37669. var ico_vertexuv = [
  37670. 5, 1, 3, 1, 6, 4, 0, 0,
  37671. 5, 3, 4, 2, 2, 2, 4, 0,
  37672. 2, 0, 1, 1, 6, 0, 6, 2,
  37673. // vertex alias (for same vertex on different faces)
  37674. 0, 4,
  37675. 3, 3,
  37676. 4, 4,
  37677. 3, 1,
  37678. 4, 2,
  37679. 4, 4,
  37680. 0, 2,
  37681. 1, 1,
  37682. 2, 2,
  37683. 3, 3,
  37684. 1, 3,
  37685. 2, 4 // 23: B + 12
  37686. ];
  37687. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37688. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37689. // First island of uv mapping
  37690. // v = 4h 3+ 2
  37691. // v = 3h 9+ 4
  37692. // v = 2h 9+ 5 B
  37693. // v = 1h 9 1 0
  37694. // v = 0h 3 8 7 A
  37695. // u = 0 1 2 3 4 5 6 *a
  37696. // Second island of uv mapping
  37697. // v = 4h 0+ B+ 4+
  37698. // v = 3h A+ 2+
  37699. // v = 2h 7+ 6 3+
  37700. // v = 1h 8+ 3+
  37701. // v = 0h
  37702. // u = 0 1 2 3 4 5 6 *a
  37703. // Face layout on texture UV mapping
  37704. // ============
  37705. // \ 4 /\ 16 / ======
  37706. // \ / \ / /\ 11 /
  37707. // \/ 7 \/ / \ /
  37708. // ======= / 10 \/
  37709. // /\ 17 /\ =======
  37710. // / \ / \ \ 15 /\
  37711. // / 8 \/ 12 \ \ / \
  37712. // ============ \/ 6 \
  37713. // \ 18 /\ ============
  37714. // \ / \ \ 5 /\ 0 /
  37715. // \/ 13 \ \ / \ /
  37716. // ======= \/ 1 \/
  37717. // =============
  37718. // /\ 19 /\ 2 /\
  37719. // / \ / \ / \
  37720. // / 14 \/ 9 \/ 3 \
  37721. // ===================
  37722. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37723. var ustep = 138 / 1024;
  37724. var vstep = 239 / 1024;
  37725. var uoffset = 60 / 1024;
  37726. var voffset = 26 / 1024;
  37727. // Second island should have margin, not to touch the first island
  37728. // avoid any borderline artefact in pixel rounding
  37729. var island_u_offset = -40 / 1024;
  37730. var island_v_offset = +20 / 1024;
  37731. // face is either island 0 or 1 :
  37732. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37733. var island = [
  37734. 0, 0, 0, 0, 1,
  37735. 0, 0, 1, 1, 0,
  37736. 0, 0, 1, 1, 0,
  37737. 0, 1, 1, 1, 0 // 15 - 19
  37738. ];
  37739. var indices = new Array();
  37740. var positions = new Array();
  37741. var normals = new Array();
  37742. var uvs = new Array();
  37743. var current_indice = 0;
  37744. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37745. var face_vertex_pos = new Array(3);
  37746. var face_vertex_uv = new Array(3);
  37747. var v012;
  37748. for (v012 = 0; v012 < 3; v012++) {
  37749. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37750. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37751. }
  37752. // create all with normals
  37753. for (var face = 0; face < 20; face++) {
  37754. // 3 vertex per face
  37755. for (v012 = 0; v012 < 3; v012++) {
  37756. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37757. var v_id = ico_indices[3 * face + v012];
  37758. // vertex have 3D position (x,y,z)
  37759. 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]);
  37760. // Normalize to get normal, then scale to radius
  37761. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37762. // uv Coordinates from vertex ID
  37763. 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);
  37764. }
  37765. // Subdivide the face (interpolate pos, norm, uv)
  37766. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37767. // - norm is linear interpolation of vertex corner normal
  37768. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37769. // - uv is linear interpolation
  37770. //
  37771. // Topology is as below for sub-divide by 2
  37772. // vertex shown as v0,v1,v2
  37773. // interp index is i1 to progress in range [v0,v1[
  37774. // interp index is i2 to progress in range [v0,v2[
  37775. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37776. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37777. //
  37778. //
  37779. // i2 v2
  37780. // ^ ^
  37781. // / / \
  37782. // / / \
  37783. // / / \
  37784. // / / (0,1) \
  37785. // / #---------\
  37786. // / / \ (0,0)'/ \
  37787. // / / \ / \
  37788. // / / \ / \
  37789. // / / (0,0) \ / (1,0) \
  37790. // / #---------#---------\
  37791. // v0 v1
  37792. //
  37793. // --------------------> i1
  37794. //
  37795. // interp of (i1,i2):
  37796. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37797. // along i1 : lerp(x0,x1, i1/(S-i2))
  37798. //
  37799. // centroid of triangle is needed to get help normal computation
  37800. // (c1,c2) are used for centroid location
  37801. var interp_vertex = function (i1, i2, c1, c2) {
  37802. // vertex is interpolated from
  37803. // - face_vertex_pos[0..2]
  37804. // - face_vertex_uv[0..2]
  37805. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37806. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37807. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37808. pos_interp.normalize();
  37809. var vertex_normal;
  37810. if (flat) {
  37811. // in flat mode, recalculate normal as face centroid normal
  37812. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37813. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37814. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37815. }
  37816. else {
  37817. // in smooth mode, recalculate normal from each single vertex position
  37818. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37819. }
  37820. // Vertex normal need correction due to X,Y,Z radius scaling
  37821. vertex_normal.x /= radiusX;
  37822. vertex_normal.y /= radiusY;
  37823. vertex_normal.z /= radiusZ;
  37824. vertex_normal.normalize();
  37825. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37826. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37827. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37828. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37829. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37830. uvs.push(uv_interp.x, uv_interp.y);
  37831. // push each vertex has member of a face
  37832. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37833. indices.push(current_indice);
  37834. current_indice++;
  37835. };
  37836. for (var i2 = 0; i2 < subdivisions; i2++) {
  37837. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37838. // face : (i1,i2) for /\ :
  37839. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37840. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37841. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37842. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37843. if (i1 + i2 + 1 < subdivisions) {
  37844. // face : (i1,i2)' for \/ :
  37845. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37846. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37847. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37848. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37849. }
  37850. }
  37851. }
  37852. }
  37853. // Sides
  37854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37855. // Result
  37856. var vertexData = new VertexData();
  37857. vertexData.indices = indices;
  37858. vertexData.positions = positions;
  37859. vertexData.normals = normals;
  37860. vertexData.uvs = uvs;
  37861. return vertexData;
  37862. };
  37863. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37864. /**
  37865. * Creates the VertexData for a Polyhedron
  37866. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37867. * * type provided types are:
  37868. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37869. * * 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)
  37870. * * size the size of the IcoSphere, optional default 1
  37871. * * sizeX allows stretching in the x direction, optional, default size
  37872. * * sizeY allows stretching in the y direction, optional, default size
  37873. * * sizeZ allows stretching in the z direction, optional, default size
  37874. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37875. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37876. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37877. * * flat when true creates a flat shaded mesh, optional, default true
  37878. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37879. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37880. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37881. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37882. * @returns the VertexData of the Polyhedron
  37883. */
  37884. VertexData.CreatePolyhedron = function (options) {
  37885. // provided polyhedron types :
  37886. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37887. // 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)
  37888. var polyhedra = [];
  37889. 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]] };
  37890. 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]] };
  37891. polyhedra[2] = {
  37892. 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]],
  37893. 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]]
  37894. };
  37895. polyhedra[3] = {
  37896. 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]],
  37897. 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]]
  37898. };
  37899. polyhedra[4] = {
  37900. 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]],
  37901. 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]]
  37902. };
  37903. 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]] };
  37904. 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]] };
  37905. 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]] };
  37906. 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]] };
  37907. 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]] };
  37908. 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]] };
  37909. 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]] };
  37910. 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]] };
  37911. 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]] };
  37912. polyhedra[14] = {
  37913. 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]],
  37914. 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]]
  37915. };
  37916. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37917. var size = options.size;
  37918. var sizeX = options.sizeX || size || 1;
  37919. var sizeY = options.sizeY || size || 1;
  37920. var sizeZ = options.sizeZ || size || 1;
  37921. var data = options.custom || polyhedra[type];
  37922. var nbfaces = data.face.length;
  37923. var faceUV = options.faceUV || new Array(nbfaces);
  37924. var faceColors = options.faceColors;
  37925. var flat = (options.flat === undefined) ? true : options.flat;
  37926. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37927. var positions = new Array();
  37928. var indices = new Array();
  37929. var normals = new Array();
  37930. var uvs = new Array();
  37931. var colors = new Array();
  37932. var index = 0;
  37933. var faceIdx = 0; // face cursor in the array "indexes"
  37934. var indexes = new Array();
  37935. var i = 0;
  37936. var f = 0;
  37937. var u, v, ang, x, y, tmp;
  37938. // default face colors and UV if undefined
  37939. if (flat) {
  37940. for (f = 0; f < nbfaces; f++) {
  37941. if (faceColors && faceColors[f] === undefined) {
  37942. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37943. }
  37944. if (faceUV && faceUV[f] === undefined) {
  37945. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37946. }
  37947. }
  37948. }
  37949. if (!flat) {
  37950. for (i = 0; i < data.vertex.length; i++) {
  37951. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37952. uvs.push(0, 0);
  37953. }
  37954. for (f = 0; f < nbfaces; f++) {
  37955. for (i = 0; i < data.face[f].length - 2; i++) {
  37956. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37957. }
  37958. }
  37959. }
  37960. else {
  37961. for (f = 0; f < nbfaces; f++) {
  37962. var fl = data.face[f].length; // number of vertices of the current face
  37963. ang = 2 * Math.PI / fl;
  37964. x = 0.5 * Math.tan(ang / 2);
  37965. y = 0.5;
  37966. // positions, uvs, colors
  37967. for (i = 0; i < fl; i++) {
  37968. // positions
  37969. 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);
  37970. indexes.push(index);
  37971. index++;
  37972. // uvs
  37973. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37974. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37975. uvs.push(u, v);
  37976. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37977. y = x * Math.sin(ang) + y * Math.cos(ang);
  37978. x = tmp;
  37979. // colors
  37980. if (faceColors) {
  37981. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37982. }
  37983. }
  37984. // indices from indexes
  37985. for (i = 0; i < fl - 2; i++) {
  37986. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37987. }
  37988. faceIdx += fl;
  37989. }
  37990. }
  37991. VertexData.ComputeNormals(positions, indices, normals);
  37992. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37993. var vertexData = new VertexData();
  37994. vertexData.positions = positions;
  37995. vertexData.indices = indices;
  37996. vertexData.normals = normals;
  37997. vertexData.uvs = uvs;
  37998. if (faceColors && flat) {
  37999. vertexData.colors = colors;
  38000. }
  38001. return vertexData;
  38002. };
  38003. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38004. /**
  38005. * Creates the VertexData for a TorusKnot
  38006. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38007. * * radius the radius of the torus knot, optional, default 2
  38008. * * tube the thickness of the tube, optional, default 0.5
  38009. * * radialSegments the number of sides on each tube segments, optional, default 32
  38010. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38011. * * p the number of windings around the z axis, optional, default 2
  38012. * * q the number of windings around the x axis, optional, default 3
  38013. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38014. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38015. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38016. * @returns the VertexData of the Torus Knot
  38017. */
  38018. VertexData.CreateTorusKnot = function (options) {
  38019. var indices = new Array();
  38020. var positions = new Array();
  38021. var normals = new Array();
  38022. var uvs = new Array();
  38023. var radius = options.radius || 2;
  38024. var tube = options.tube || 0.5;
  38025. var radialSegments = options.radialSegments || 32;
  38026. var tubularSegments = options.tubularSegments || 32;
  38027. var p = options.p || 2;
  38028. var q = options.q || 3;
  38029. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38030. // Helper
  38031. var getPos = function (angle) {
  38032. var cu = Math.cos(angle);
  38033. var su = Math.sin(angle);
  38034. var quOverP = q / p * angle;
  38035. var cs = Math.cos(quOverP);
  38036. var tx = radius * (2 + cs) * 0.5 * cu;
  38037. var ty = radius * (2 + cs) * su * 0.5;
  38038. var tz = radius * Math.sin(quOverP) * 0.5;
  38039. return new BABYLON.Vector3(tx, ty, tz);
  38040. };
  38041. // Vertices
  38042. var i;
  38043. var j;
  38044. for (i = 0; i <= radialSegments; i++) {
  38045. var modI = i % radialSegments;
  38046. var u = modI / radialSegments * 2 * p * Math.PI;
  38047. var p1 = getPos(u);
  38048. var p2 = getPos(u + 0.01);
  38049. var tang = p2.subtract(p1);
  38050. var n = p2.add(p1);
  38051. var bitan = BABYLON.Vector3.Cross(tang, n);
  38052. n = BABYLON.Vector3.Cross(bitan, tang);
  38053. bitan.normalize();
  38054. n.normalize();
  38055. for (j = 0; j < tubularSegments; j++) {
  38056. var modJ = j % tubularSegments;
  38057. var v = modJ / tubularSegments * 2 * Math.PI;
  38058. var cx = -tube * Math.cos(v);
  38059. var cy = tube * Math.sin(v);
  38060. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38061. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38062. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38063. uvs.push(i / radialSegments);
  38064. uvs.push(j / tubularSegments);
  38065. }
  38066. }
  38067. for (i = 0; i < radialSegments; i++) {
  38068. for (j = 0; j < tubularSegments; j++) {
  38069. var jNext = (j + 1) % tubularSegments;
  38070. var a = i * tubularSegments + j;
  38071. var b = (i + 1) * tubularSegments + j;
  38072. var c = (i + 1) * tubularSegments + jNext;
  38073. var d = i * tubularSegments + jNext;
  38074. indices.push(d);
  38075. indices.push(b);
  38076. indices.push(a);
  38077. indices.push(d);
  38078. indices.push(c);
  38079. indices.push(b);
  38080. }
  38081. }
  38082. // Normals
  38083. VertexData.ComputeNormals(positions, indices, normals);
  38084. // Sides
  38085. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38086. // Result
  38087. var vertexData = new VertexData();
  38088. vertexData.indices = indices;
  38089. vertexData.positions = positions;
  38090. vertexData.normals = normals;
  38091. vertexData.uvs = uvs;
  38092. return vertexData;
  38093. };
  38094. // Tools
  38095. /**
  38096. * Compute normals for given positions and indices
  38097. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38098. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38099. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38100. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38101. * * facetNormals : optional array of facet normals (vector3)
  38102. * * facetPositions : optional array of facet positions (vector3)
  38103. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38104. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38105. * * bInfo : optional bounding info, required for facetPartitioning computation
  38106. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38107. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38108. * * useRightHandedSystem: optional boolean to for right handed system computation
  38109. * * depthSort : optional boolean to enable the facet depth sort computation
  38110. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38111. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38112. */
  38113. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38114. // temporary scalar variables
  38115. var index = 0; // facet index
  38116. var p1p2x = 0.0; // p1p2 vector x coordinate
  38117. var p1p2y = 0.0; // p1p2 vector y coordinate
  38118. var p1p2z = 0.0; // p1p2 vector z coordinate
  38119. var p3p2x = 0.0; // p3p2 vector x coordinate
  38120. var p3p2y = 0.0; // p3p2 vector y coordinate
  38121. var p3p2z = 0.0; // p3p2 vector z coordinate
  38122. var faceNormalx = 0.0; // facet normal x coordinate
  38123. var faceNormaly = 0.0; // facet normal y coordinate
  38124. var faceNormalz = 0.0; // facet normal z coordinate
  38125. var length = 0.0; // facet normal length before normalization
  38126. var v1x = 0; // vector1 x index in the positions array
  38127. var v1y = 0; // vector1 y index in the positions array
  38128. var v1z = 0; // vector1 z index in the positions array
  38129. var v2x = 0; // vector2 x index in the positions array
  38130. var v2y = 0; // vector2 y index in the positions array
  38131. var v2z = 0; // vector2 z index in the positions array
  38132. var v3x = 0; // vector3 x index in the positions array
  38133. var v3y = 0; // vector3 y index in the positions array
  38134. var v3z = 0; // vector3 z index in the positions array
  38135. var computeFacetNormals = false;
  38136. var computeFacetPositions = false;
  38137. var computeFacetPartitioning = false;
  38138. var computeDepthSort = false;
  38139. var faceNormalSign = 1;
  38140. var ratio = 0;
  38141. var distanceTo = null;
  38142. if (options) {
  38143. computeFacetNormals = (options.facetNormals) ? true : false;
  38144. computeFacetPositions = (options.facetPositions) ? true : false;
  38145. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38146. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38147. ratio = options.ratio || 0;
  38148. computeDepthSort = (options.depthSort) ? true : false;
  38149. distanceTo = (options.distanceTo);
  38150. if (computeDepthSort) {
  38151. if (distanceTo === undefined) {
  38152. distanceTo = BABYLON.Vector3.Zero();
  38153. }
  38154. var depthSortedFacets = options.depthSortedFacets;
  38155. }
  38156. }
  38157. // facetPartitioning reinit if needed
  38158. var xSubRatio = 0;
  38159. var ySubRatio = 0;
  38160. var zSubRatio = 0;
  38161. var subSq = 0;
  38162. if (computeFacetPartitioning && options && options.bbSize) {
  38163. var ox = 0; // X partitioning index for facet position
  38164. var oy = 0; // Y partinioning index for facet position
  38165. var oz = 0; // Z partinioning index for facet position
  38166. var b1x = 0; // X partitioning index for facet v1 vertex
  38167. var b1y = 0; // Y partitioning index for facet v1 vertex
  38168. var b1z = 0; // z partitioning index for facet v1 vertex
  38169. var b2x = 0; // X partitioning index for facet v2 vertex
  38170. var b2y = 0; // Y partitioning index for facet v2 vertex
  38171. var b2z = 0; // Z partitioning index for facet v2 vertex
  38172. var b3x = 0; // X partitioning index for facet v3 vertex
  38173. var b3y = 0; // Y partitioning index for facet v3 vertex
  38174. var b3z = 0; // Z partitioning index for facet v3 vertex
  38175. var block_idx_o = 0; // facet barycenter block index
  38176. var block_idx_v1 = 0; // v1 vertex block index
  38177. var block_idx_v2 = 0; // v2 vertex block index
  38178. var block_idx_v3 = 0; // v3 vertex block index
  38179. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38180. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38181. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38182. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38183. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38184. subSq = options.subDiv.max * options.subDiv.max;
  38185. options.facetPartitioning.length = 0;
  38186. }
  38187. // reset the normals
  38188. for (index = 0; index < positions.length; index++) {
  38189. normals[index] = 0.0;
  38190. }
  38191. // Loop : 1 indice triplet = 1 facet
  38192. var nbFaces = (indices.length / 3) | 0;
  38193. for (index = 0; index < nbFaces; index++) {
  38194. // get the indexes of the coordinates of each vertex of the facet
  38195. v1x = indices[index * 3] * 3;
  38196. v1y = v1x + 1;
  38197. v1z = v1x + 2;
  38198. v2x = indices[index * 3 + 1] * 3;
  38199. v2y = v2x + 1;
  38200. v2z = v2x + 2;
  38201. v3x = indices[index * 3 + 2] * 3;
  38202. v3y = v3x + 1;
  38203. v3z = v3x + 2;
  38204. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38205. p1p2y = positions[v1y] - positions[v2y];
  38206. p1p2z = positions[v1z] - positions[v2z];
  38207. p3p2x = positions[v3x] - positions[v2x];
  38208. p3p2y = positions[v3y] - positions[v2y];
  38209. p3p2z = positions[v3z] - positions[v2z];
  38210. // compute the face normal with the cross product
  38211. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38212. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38213. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38214. // normalize this normal and store it in the array facetData
  38215. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38216. length = (length === 0) ? 1.0 : length;
  38217. faceNormalx /= length;
  38218. faceNormaly /= length;
  38219. faceNormalz /= length;
  38220. if (computeFacetNormals && options) {
  38221. options.facetNormals[index].x = faceNormalx;
  38222. options.facetNormals[index].y = faceNormaly;
  38223. options.facetNormals[index].z = faceNormalz;
  38224. }
  38225. if (computeFacetPositions && options) {
  38226. // compute and the facet barycenter coordinates in the array facetPositions
  38227. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38228. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38229. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38230. }
  38231. if (computeFacetPartitioning && options) {
  38232. // store the facet indexes in arrays in the main facetPartitioning array :
  38233. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38234. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38235. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38236. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38237. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38238. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38239. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38240. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38241. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38242. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38243. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38244. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38245. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38246. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38247. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38248. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38249. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38250. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38251. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38252. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38253. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38254. // push each facet index in each block containing the vertex
  38255. options.facetPartitioning[block_idx_v1].push(index);
  38256. if (block_idx_v2 != block_idx_v1) {
  38257. options.facetPartitioning[block_idx_v2].push(index);
  38258. }
  38259. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38260. options.facetPartitioning[block_idx_v3].push(index);
  38261. }
  38262. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38263. options.facetPartitioning[block_idx_o].push(index);
  38264. }
  38265. }
  38266. if (computeDepthSort && options && options.facetPositions) {
  38267. var dsf = depthSortedFacets[index];
  38268. dsf.ind = index * 3;
  38269. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38270. }
  38271. // compute the normals anyway
  38272. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38273. normals[v1y] += faceNormaly;
  38274. normals[v1z] += faceNormalz;
  38275. normals[v2x] += faceNormalx;
  38276. normals[v2y] += faceNormaly;
  38277. normals[v2z] += faceNormalz;
  38278. normals[v3x] += faceNormalx;
  38279. normals[v3y] += faceNormaly;
  38280. normals[v3z] += faceNormalz;
  38281. }
  38282. // last normalization of each normal
  38283. for (index = 0; index < normals.length / 3; index++) {
  38284. faceNormalx = normals[index * 3];
  38285. faceNormaly = normals[index * 3 + 1];
  38286. faceNormalz = normals[index * 3 + 2];
  38287. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38288. length = (length === 0) ? 1.0 : length;
  38289. faceNormalx /= length;
  38290. faceNormaly /= length;
  38291. faceNormalz /= length;
  38292. normals[index * 3] = faceNormalx;
  38293. normals[index * 3 + 1] = faceNormaly;
  38294. normals[index * 3 + 2] = faceNormalz;
  38295. }
  38296. };
  38297. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38298. var li = indices.length;
  38299. var ln = normals.length;
  38300. var i;
  38301. var n;
  38302. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38303. switch (sideOrientation) {
  38304. case BABYLON.Mesh.FRONTSIDE:
  38305. // nothing changed
  38306. break;
  38307. case BABYLON.Mesh.BACKSIDE:
  38308. var tmp;
  38309. // indices
  38310. for (i = 0; i < li; i += 3) {
  38311. tmp = indices[i];
  38312. indices[i] = indices[i + 2];
  38313. indices[i + 2] = tmp;
  38314. }
  38315. // normals
  38316. for (n = 0; n < ln; n++) {
  38317. normals[n] = -normals[n];
  38318. }
  38319. break;
  38320. case BABYLON.Mesh.DOUBLESIDE:
  38321. // positions
  38322. var lp = positions.length;
  38323. var l = lp / 3;
  38324. for (var p = 0; p < lp; p++) {
  38325. positions[lp + p] = positions[p];
  38326. }
  38327. // indices
  38328. for (i = 0; i < li; i += 3) {
  38329. indices[i + li] = indices[i + 2] + l;
  38330. indices[i + 1 + li] = indices[i + 1] + l;
  38331. indices[i + 2 + li] = indices[i] + l;
  38332. }
  38333. // normals
  38334. for (n = 0; n < ln; n++) {
  38335. normals[ln + n] = -normals[n];
  38336. }
  38337. // uvs
  38338. var lu = uvs.length;
  38339. var u = 0;
  38340. for (u = 0; u < lu; u++) {
  38341. uvs[u + lu] = uvs[u];
  38342. }
  38343. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38344. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38345. u = 0;
  38346. for (i = 0; i < lu / 2; i++) {
  38347. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38348. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38349. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38350. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38351. u += 2;
  38352. }
  38353. break;
  38354. }
  38355. };
  38356. /**
  38357. * Applies VertexData created from the imported parameters to the geometry
  38358. * @param parsedVertexData the parsed data from an imported file
  38359. * @param geometry the geometry to apply the VertexData to
  38360. */
  38361. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38362. var vertexData = new VertexData();
  38363. // positions
  38364. var positions = parsedVertexData.positions;
  38365. if (positions) {
  38366. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38367. }
  38368. // normals
  38369. var normals = parsedVertexData.normals;
  38370. if (normals) {
  38371. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38372. }
  38373. // tangents
  38374. var tangents = parsedVertexData.tangents;
  38375. if (tangents) {
  38376. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38377. }
  38378. // uvs
  38379. var uvs = parsedVertexData.uvs;
  38380. if (uvs) {
  38381. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38382. }
  38383. // uv2s
  38384. var uv2s = parsedVertexData.uv2s;
  38385. if (uv2s) {
  38386. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38387. }
  38388. // uv3s
  38389. var uv3s = parsedVertexData.uv3s;
  38390. if (uv3s) {
  38391. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38392. }
  38393. // uv4s
  38394. var uv4s = parsedVertexData.uv4s;
  38395. if (uv4s) {
  38396. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38397. }
  38398. // uv5s
  38399. var uv5s = parsedVertexData.uv5s;
  38400. if (uv5s) {
  38401. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38402. }
  38403. // uv6s
  38404. var uv6s = parsedVertexData.uv6s;
  38405. if (uv6s) {
  38406. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38407. }
  38408. // colors
  38409. var colors = parsedVertexData.colors;
  38410. if (colors) {
  38411. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38412. }
  38413. // matricesIndices
  38414. var matricesIndices = parsedVertexData.matricesIndices;
  38415. if (matricesIndices) {
  38416. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38417. }
  38418. // matricesWeights
  38419. var matricesWeights = parsedVertexData.matricesWeights;
  38420. if (matricesWeights) {
  38421. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38422. }
  38423. // indices
  38424. var indices = parsedVertexData.indices;
  38425. if (indices) {
  38426. vertexData.indices = indices;
  38427. }
  38428. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38429. };
  38430. return VertexData;
  38431. }());
  38432. BABYLON.VertexData = VertexData;
  38433. })(BABYLON || (BABYLON = {}));
  38434. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38435. var BABYLON;
  38436. (function (BABYLON) {
  38437. /**
  38438. * Class used to store geometry data (vertex buffers + index buffer)
  38439. */
  38440. var Geometry = /** @class */ (function () {
  38441. /**
  38442. * Creates a new geometry
  38443. * @param id defines the unique ID
  38444. * @param scene defines the hosting scene
  38445. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38446. * @param updatable defines if geometry must be updatable (false by default)
  38447. * @param mesh defines the mesh that will be associated with the geometry
  38448. */
  38449. function Geometry(id, scene, vertexData, updatable, mesh) {
  38450. if (updatable === void 0) { updatable = false; }
  38451. if (mesh === void 0) { mesh = null; }
  38452. /**
  38453. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38454. */
  38455. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38456. this._totalVertices = 0;
  38457. this._isDisposed = false;
  38458. this._indexBufferIsUpdatable = false;
  38459. this.id = id;
  38460. this._engine = scene.getEngine();
  38461. this._meshes = [];
  38462. this._scene = scene;
  38463. //Init vertex buffer cache
  38464. this._vertexBuffers = {};
  38465. this._indices = [];
  38466. this._updatable = updatable;
  38467. // vertexData
  38468. if (vertexData) {
  38469. this.setAllVerticesData(vertexData, updatable);
  38470. }
  38471. else {
  38472. this._totalVertices = 0;
  38473. this._indices = [];
  38474. }
  38475. if (this._engine.getCaps().vertexArrayObject) {
  38476. this._vertexArrayObjects = {};
  38477. }
  38478. // applyToMesh
  38479. if (mesh) {
  38480. if (mesh.getClassName() === "LinesMesh") {
  38481. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38482. this._updateExtend();
  38483. }
  38484. this.applyToMesh(mesh);
  38485. mesh.computeWorldMatrix(true);
  38486. }
  38487. }
  38488. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38489. /**
  38490. * 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
  38491. */
  38492. get: function () {
  38493. return this._boundingBias;
  38494. },
  38495. /**
  38496. * 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
  38497. */
  38498. set: function (value) {
  38499. if (this._boundingBias && this._boundingBias.equals(value)) {
  38500. return;
  38501. }
  38502. this._boundingBias = value.clone();
  38503. this._updateBoundingInfo(true, null);
  38504. },
  38505. enumerable: true,
  38506. configurable: true
  38507. });
  38508. /**
  38509. * Static function used to attach a new empty geometry to a mesh
  38510. * @param mesh defines the mesh to attach the geometry to
  38511. * @returns the new {BABYLON.Geometry}
  38512. */
  38513. Geometry.CreateGeometryForMesh = function (mesh) {
  38514. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38515. geometry.applyToMesh(mesh);
  38516. return geometry;
  38517. };
  38518. Object.defineProperty(Geometry.prototype, "extend", {
  38519. /**
  38520. * Gets the current extend of the geometry
  38521. */
  38522. get: function () {
  38523. return this._extend;
  38524. },
  38525. enumerable: true,
  38526. configurable: true
  38527. });
  38528. /**
  38529. * Gets the hosting scene
  38530. * @returns the hosting {BABYLON.Scene}
  38531. */
  38532. Geometry.prototype.getScene = function () {
  38533. return this._scene;
  38534. };
  38535. /**
  38536. * Gets the hosting engine
  38537. * @returns the hosting {BABYLON.Engine}
  38538. */
  38539. Geometry.prototype.getEngine = function () {
  38540. return this._engine;
  38541. };
  38542. /**
  38543. * Defines if the geometry is ready to use
  38544. * @returns true if the geometry is ready to be used
  38545. */
  38546. Geometry.prototype.isReady = function () {
  38547. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38548. };
  38549. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38550. /**
  38551. * Gets a value indicating that the geometry should not be serialized
  38552. */
  38553. get: function () {
  38554. for (var index = 0; index < this._meshes.length; index++) {
  38555. if (!this._meshes[index].doNotSerialize) {
  38556. return false;
  38557. }
  38558. }
  38559. return true;
  38560. },
  38561. enumerable: true,
  38562. configurable: true
  38563. });
  38564. /** @hidden */
  38565. Geometry.prototype._rebuild = function () {
  38566. if (this._vertexArrayObjects) {
  38567. this._vertexArrayObjects = {};
  38568. }
  38569. // Index buffer
  38570. if (this._meshes.length !== 0 && this._indices) {
  38571. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38572. }
  38573. // Vertex buffers
  38574. for (var key in this._vertexBuffers) {
  38575. var vertexBuffer = this._vertexBuffers[key];
  38576. vertexBuffer._rebuild();
  38577. }
  38578. };
  38579. /**
  38580. * Affects all gemetry data in one call
  38581. * @param vertexData defines the geometry data
  38582. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38583. */
  38584. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38585. vertexData.applyToGeometry(this, updatable);
  38586. this.notifyUpdate();
  38587. };
  38588. /**
  38589. * Set specific vertex data
  38590. * @param kind defines the data kind (Position, normal, etc...)
  38591. * @param data defines the vertex data to use
  38592. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38593. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38594. */
  38595. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38596. if (updatable === void 0) { updatable = false; }
  38597. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38598. this.setVerticesBuffer(buffer);
  38599. };
  38600. /**
  38601. * Removes a specific vertex data
  38602. * @param kind defines the data kind (Position, normal, etc...)
  38603. */
  38604. Geometry.prototype.removeVerticesData = function (kind) {
  38605. if (this._vertexBuffers[kind]) {
  38606. this._vertexBuffers[kind].dispose();
  38607. delete this._vertexBuffers[kind];
  38608. }
  38609. };
  38610. /**
  38611. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38612. * @param buffer defines the vertex buffer to use
  38613. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38614. */
  38615. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38616. if (totalVertices === void 0) { totalVertices = null; }
  38617. var kind = buffer.getKind();
  38618. if (this._vertexBuffers[kind]) {
  38619. this._vertexBuffers[kind].dispose();
  38620. }
  38621. this._vertexBuffers[kind] = buffer;
  38622. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38623. var data = buffer.getData();
  38624. if (totalVertices != null) {
  38625. this._totalVertices = totalVertices;
  38626. }
  38627. else {
  38628. if (data != null) {
  38629. this._totalVertices = data.length / (buffer.byteStride / 4);
  38630. }
  38631. }
  38632. this._updateExtend(data);
  38633. this._resetPointsArrayCache();
  38634. var meshes = this._meshes;
  38635. var numOfMeshes = meshes.length;
  38636. for (var index = 0; index < numOfMeshes; index++) {
  38637. var mesh = meshes[index];
  38638. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38639. mesh._createGlobalSubMesh(false);
  38640. mesh.computeWorldMatrix(true);
  38641. }
  38642. }
  38643. this.notifyUpdate(kind);
  38644. if (this._vertexArrayObjects) {
  38645. this._disposeVertexArrayObjects();
  38646. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38647. }
  38648. };
  38649. /**
  38650. * Update a specific vertex buffer
  38651. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38652. * It will do nothing if the buffer is not updatable
  38653. * @param kind defines the data kind (Position, normal, etc...)
  38654. * @param data defines the data to use
  38655. * @param offset defines the offset in the target buffer where to store the data
  38656. * @param useBytes set to true if the offset is in bytes
  38657. */
  38658. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38659. if (useBytes === void 0) { useBytes = false; }
  38660. var vertexBuffer = this.getVertexBuffer(kind);
  38661. if (!vertexBuffer) {
  38662. return;
  38663. }
  38664. vertexBuffer.updateDirectly(data, offset, useBytes);
  38665. this.notifyUpdate(kind);
  38666. };
  38667. /**
  38668. * Update a specific vertex buffer
  38669. * This function will create a new buffer if the current one is not updatable
  38670. * @param kind defines the data kind (Position, normal, etc...)
  38671. * @param data defines the data to use
  38672. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38673. */
  38674. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38675. if (updateExtends === void 0) { updateExtends = false; }
  38676. var vertexBuffer = this.getVertexBuffer(kind);
  38677. if (!vertexBuffer) {
  38678. return;
  38679. }
  38680. vertexBuffer.update(data);
  38681. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38682. this._updateBoundingInfo(updateExtends, data);
  38683. }
  38684. this.notifyUpdate(kind);
  38685. };
  38686. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38687. if (updateExtends) {
  38688. this._updateExtend(data);
  38689. }
  38690. var meshes = this._meshes;
  38691. var numOfMeshes = meshes.length;
  38692. this._resetPointsArrayCache();
  38693. for (var index = 0; index < numOfMeshes; index++) {
  38694. var mesh = meshes[index];
  38695. if (updateExtends) {
  38696. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38697. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38698. var subMesh = mesh.subMeshes[subIndex];
  38699. subMesh.refreshBoundingInfo();
  38700. }
  38701. }
  38702. }
  38703. };
  38704. /** @hidden */
  38705. Geometry.prototype._bind = function (effect, indexToBind) {
  38706. if (!effect) {
  38707. return;
  38708. }
  38709. if (indexToBind === undefined) {
  38710. indexToBind = this._indexBuffer;
  38711. }
  38712. var vbs = this.getVertexBuffers();
  38713. if (!vbs) {
  38714. return;
  38715. }
  38716. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38717. this._engine.bindBuffers(vbs, indexToBind, effect);
  38718. return;
  38719. }
  38720. // Using VAO
  38721. if (!this._vertexArrayObjects[effect.key]) {
  38722. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38723. }
  38724. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38725. };
  38726. /**
  38727. * Gets total number of vertices
  38728. * @returns the total number of vertices
  38729. */
  38730. Geometry.prototype.getTotalVertices = function () {
  38731. if (!this.isReady()) {
  38732. return 0;
  38733. }
  38734. return this._totalVertices;
  38735. };
  38736. /**
  38737. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38738. * @param kind defines the data kind (Position, normal, etc...)
  38739. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38740. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38741. * @returns a float array containing vertex data
  38742. */
  38743. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38744. var vertexBuffer = this.getVertexBuffer(kind);
  38745. if (!vertexBuffer) {
  38746. return null;
  38747. }
  38748. var data = vertexBuffer.getData();
  38749. if (!data) {
  38750. return null;
  38751. }
  38752. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38753. var count = this._totalVertices * vertexBuffer.getSize();
  38754. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38755. var copy_1 = new Array(count);
  38756. vertexBuffer.forEach(count, function (value, index) {
  38757. copy_1[index] = value;
  38758. });
  38759. return copy_1;
  38760. }
  38761. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38762. if (data instanceof Array) {
  38763. var offset = vertexBuffer.byteOffset / 4;
  38764. return BABYLON.Tools.Slice(data, offset, offset + count);
  38765. }
  38766. else if (data instanceof ArrayBuffer) {
  38767. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38768. }
  38769. else {
  38770. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38771. }
  38772. }
  38773. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38774. return BABYLON.Tools.Slice(data);
  38775. }
  38776. return data;
  38777. };
  38778. /**
  38779. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38780. * @param kind defines the data kind (Position, normal, etc...)
  38781. * @returns true if the vertex buffer with the specified kind is updatable
  38782. */
  38783. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38784. var vb = this._vertexBuffers[kind];
  38785. if (!vb) {
  38786. return false;
  38787. }
  38788. return vb.isUpdatable();
  38789. };
  38790. /**
  38791. * Gets a specific vertex buffer
  38792. * @param kind defines the data kind (Position, normal, etc...)
  38793. * @returns a {BABYLON.VertexBuffer}
  38794. */
  38795. Geometry.prototype.getVertexBuffer = function (kind) {
  38796. if (!this.isReady()) {
  38797. return null;
  38798. }
  38799. return this._vertexBuffers[kind];
  38800. };
  38801. /**
  38802. * Returns all vertex buffers
  38803. * @return an object holding all vertex buffers indexed by kind
  38804. */
  38805. Geometry.prototype.getVertexBuffers = function () {
  38806. if (!this.isReady()) {
  38807. return null;
  38808. }
  38809. return this._vertexBuffers;
  38810. };
  38811. /**
  38812. * Gets a boolean indicating if specific vertex buffer is present
  38813. * @param kind defines the data kind (Position, normal, etc...)
  38814. * @returns true if data is present
  38815. */
  38816. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38817. if (!this._vertexBuffers) {
  38818. if (this._delayInfo) {
  38819. return this._delayInfo.indexOf(kind) !== -1;
  38820. }
  38821. return false;
  38822. }
  38823. return this._vertexBuffers[kind] !== undefined;
  38824. };
  38825. /**
  38826. * Gets a list of all attached data kinds (Position, normal, etc...)
  38827. * @returns a list of string containing all kinds
  38828. */
  38829. Geometry.prototype.getVerticesDataKinds = function () {
  38830. var result = [];
  38831. var kind;
  38832. if (!this._vertexBuffers && this._delayInfo) {
  38833. for (kind in this._delayInfo) {
  38834. result.push(kind);
  38835. }
  38836. }
  38837. else {
  38838. for (kind in this._vertexBuffers) {
  38839. result.push(kind);
  38840. }
  38841. }
  38842. return result;
  38843. };
  38844. /**
  38845. * Update index buffer
  38846. * @param indices defines the indices to store in the index buffer
  38847. * @param offset defines the offset in the target buffer where to store the data
  38848. */
  38849. Geometry.prototype.updateIndices = function (indices, offset) {
  38850. if (!this._indexBuffer) {
  38851. return;
  38852. }
  38853. if (!this._indexBufferIsUpdatable) {
  38854. this.setIndices(indices, null, true);
  38855. }
  38856. else {
  38857. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38858. }
  38859. };
  38860. /**
  38861. * Creates a new index buffer
  38862. * @param indices defines the indices to store in the index buffer
  38863. * @param totalVertices defines the total number of vertices (could be null)
  38864. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38865. */
  38866. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38867. if (totalVertices === void 0) { totalVertices = null; }
  38868. if (updatable === void 0) { updatable = false; }
  38869. if (this._indexBuffer) {
  38870. this._engine._releaseBuffer(this._indexBuffer);
  38871. }
  38872. this._disposeVertexArrayObjects();
  38873. this._indices = indices;
  38874. this._indexBufferIsUpdatable = updatable;
  38875. if (this._meshes.length !== 0 && this._indices) {
  38876. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38877. }
  38878. if (totalVertices != undefined) { // including null and undefined
  38879. this._totalVertices = totalVertices;
  38880. }
  38881. var meshes = this._meshes;
  38882. var numOfMeshes = meshes.length;
  38883. for (var index = 0; index < numOfMeshes; index++) {
  38884. meshes[index]._createGlobalSubMesh(true);
  38885. }
  38886. this.notifyUpdate();
  38887. };
  38888. /**
  38889. * Return the total number of indices
  38890. * @returns the total number of indices
  38891. */
  38892. Geometry.prototype.getTotalIndices = function () {
  38893. if (!this.isReady()) {
  38894. return 0;
  38895. }
  38896. return this._indices.length;
  38897. };
  38898. /**
  38899. * Gets the index buffer array
  38900. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38901. * @returns the index buffer array
  38902. */
  38903. Geometry.prototype.getIndices = function (copyWhenShared) {
  38904. if (!this.isReady()) {
  38905. return null;
  38906. }
  38907. var orig = this._indices;
  38908. if (!copyWhenShared || this._meshes.length === 1) {
  38909. return orig;
  38910. }
  38911. else {
  38912. var len = orig.length;
  38913. var copy = [];
  38914. for (var i = 0; i < len; i++) {
  38915. copy.push(orig[i]);
  38916. }
  38917. return copy;
  38918. }
  38919. };
  38920. /**
  38921. * Gets the index buffer
  38922. * @return the index buffer
  38923. */
  38924. Geometry.prototype.getIndexBuffer = function () {
  38925. if (!this.isReady()) {
  38926. return null;
  38927. }
  38928. return this._indexBuffer;
  38929. };
  38930. /** @hidden */
  38931. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38932. if (effect === void 0) { effect = null; }
  38933. if (!effect || !this._vertexArrayObjects) {
  38934. return;
  38935. }
  38936. if (this._vertexArrayObjects[effect.key]) {
  38937. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38938. delete this._vertexArrayObjects[effect.key];
  38939. }
  38940. };
  38941. /**
  38942. * Release the associated resources for a specific mesh
  38943. * @param mesh defines the source mesh
  38944. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38945. */
  38946. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38947. var meshes = this._meshes;
  38948. var index = meshes.indexOf(mesh);
  38949. if (index === -1) {
  38950. return;
  38951. }
  38952. meshes.splice(index, 1);
  38953. mesh._geometry = null;
  38954. if (meshes.length === 0 && shouldDispose) {
  38955. this.dispose();
  38956. }
  38957. };
  38958. /**
  38959. * Apply current geometry to a given mesh
  38960. * @param mesh defines the mesh to apply geometry to
  38961. */
  38962. Geometry.prototype.applyToMesh = function (mesh) {
  38963. if (mesh._geometry === this) {
  38964. return;
  38965. }
  38966. var previousGeometry = mesh._geometry;
  38967. if (previousGeometry) {
  38968. previousGeometry.releaseForMesh(mesh);
  38969. }
  38970. var meshes = this._meshes;
  38971. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38972. mesh._geometry = this;
  38973. this._scene.pushGeometry(this);
  38974. meshes.push(mesh);
  38975. if (this.isReady()) {
  38976. this._applyToMesh(mesh);
  38977. }
  38978. else {
  38979. mesh._boundingInfo = this._boundingInfo;
  38980. }
  38981. };
  38982. Geometry.prototype._updateExtend = function (data) {
  38983. if (data === void 0) { data = null; }
  38984. if (!data) {
  38985. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38986. }
  38987. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38988. };
  38989. Geometry.prototype._applyToMesh = function (mesh) {
  38990. var numOfMeshes = this._meshes.length;
  38991. // vertexBuffers
  38992. for (var kind in this._vertexBuffers) {
  38993. if (numOfMeshes === 1) {
  38994. this._vertexBuffers[kind].create();
  38995. }
  38996. var buffer = this._vertexBuffers[kind].getBuffer();
  38997. if (buffer)
  38998. buffer.references = numOfMeshes;
  38999. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39000. if (!this._extend) {
  39001. this._updateExtend();
  39002. }
  39003. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39004. mesh._createGlobalSubMesh(false);
  39005. //bounding info was just created again, world matrix should be applied again.
  39006. mesh._updateBoundingInfo();
  39007. }
  39008. }
  39009. // indexBuffer
  39010. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39011. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39012. }
  39013. if (this._indexBuffer) {
  39014. this._indexBuffer.references = numOfMeshes;
  39015. }
  39016. };
  39017. Geometry.prototype.notifyUpdate = function (kind) {
  39018. if (this.onGeometryUpdated) {
  39019. this.onGeometryUpdated(this, kind);
  39020. }
  39021. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39022. var mesh = _a[_i];
  39023. mesh._markSubMeshesAsAttributesDirty();
  39024. }
  39025. };
  39026. /**
  39027. * Load the geometry if it was flagged as delay loaded
  39028. * @param scene defines the hosting scene
  39029. * @param onLoaded defines a callback called when the geometry is loaded
  39030. */
  39031. Geometry.prototype.load = function (scene, onLoaded) {
  39032. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39033. return;
  39034. }
  39035. if (this.isReady()) {
  39036. if (onLoaded) {
  39037. onLoaded();
  39038. }
  39039. return;
  39040. }
  39041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39042. this._queueLoad(scene, onLoaded);
  39043. };
  39044. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39045. var _this = this;
  39046. if (!this.delayLoadingFile) {
  39047. return;
  39048. }
  39049. scene._addPendingData(this);
  39050. scene._loadFile(this.delayLoadingFile, function (data) {
  39051. if (!_this._delayLoadingFunction) {
  39052. return;
  39053. }
  39054. _this._delayLoadingFunction(JSON.parse(data), _this);
  39055. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39056. _this._delayInfo = [];
  39057. scene._removePendingData(_this);
  39058. var meshes = _this._meshes;
  39059. var numOfMeshes = meshes.length;
  39060. for (var index = 0; index < numOfMeshes; index++) {
  39061. _this._applyToMesh(meshes[index]);
  39062. }
  39063. if (onLoaded) {
  39064. onLoaded();
  39065. }
  39066. }, undefined, true);
  39067. };
  39068. /**
  39069. * Invert the geometry to move from a right handed system to a left handed one.
  39070. */
  39071. Geometry.prototype.toLeftHanded = function () {
  39072. // Flip faces
  39073. var tIndices = this.getIndices(false);
  39074. if (tIndices != null && tIndices.length > 0) {
  39075. for (var i = 0; i < tIndices.length; i += 3) {
  39076. var tTemp = tIndices[i + 0];
  39077. tIndices[i + 0] = tIndices[i + 2];
  39078. tIndices[i + 2] = tTemp;
  39079. }
  39080. this.setIndices(tIndices);
  39081. }
  39082. // Negate position.z
  39083. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39084. if (tPositions != null && tPositions.length > 0) {
  39085. for (var i = 0; i < tPositions.length; i += 3) {
  39086. tPositions[i + 2] = -tPositions[i + 2];
  39087. }
  39088. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39089. }
  39090. // Negate normal.z
  39091. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39092. if (tNormals != null && tNormals.length > 0) {
  39093. for (var i = 0; i < tNormals.length; i += 3) {
  39094. tNormals[i + 2] = -tNormals[i + 2];
  39095. }
  39096. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39097. }
  39098. };
  39099. // Cache
  39100. /** @hidden */
  39101. Geometry.prototype._resetPointsArrayCache = function () {
  39102. this._positions = null;
  39103. };
  39104. /** @hidden */
  39105. Geometry.prototype._generatePointsArray = function () {
  39106. if (this._positions)
  39107. return true;
  39108. this._positions = [];
  39109. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39110. if (!data) {
  39111. return false;
  39112. }
  39113. for (var index = 0; index < data.length; index += 3) {
  39114. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39115. }
  39116. return true;
  39117. };
  39118. /**
  39119. * Gets a value indicating if the geometry is disposed
  39120. * @returns true if the geometry was disposed
  39121. */
  39122. Geometry.prototype.isDisposed = function () {
  39123. return this._isDisposed;
  39124. };
  39125. Geometry.prototype._disposeVertexArrayObjects = function () {
  39126. if (this._vertexArrayObjects) {
  39127. for (var kind in this._vertexArrayObjects) {
  39128. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39129. }
  39130. this._vertexArrayObjects = {};
  39131. }
  39132. };
  39133. /**
  39134. * Free all associated resources
  39135. */
  39136. Geometry.prototype.dispose = function () {
  39137. var meshes = this._meshes;
  39138. var numOfMeshes = meshes.length;
  39139. var index;
  39140. for (index = 0; index < numOfMeshes; index++) {
  39141. this.releaseForMesh(meshes[index]);
  39142. }
  39143. this._meshes = [];
  39144. this._disposeVertexArrayObjects();
  39145. for (var kind in this._vertexBuffers) {
  39146. this._vertexBuffers[kind].dispose();
  39147. }
  39148. this._vertexBuffers = {};
  39149. this._totalVertices = 0;
  39150. if (this._indexBuffer) {
  39151. this._engine._releaseBuffer(this._indexBuffer);
  39152. }
  39153. this._indexBuffer = null;
  39154. this._indices = [];
  39155. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39156. this.delayLoadingFile = null;
  39157. this._delayLoadingFunction = null;
  39158. this._delayInfo = [];
  39159. this._boundingInfo = null;
  39160. this._scene.removeGeometry(this);
  39161. this._isDisposed = true;
  39162. };
  39163. /**
  39164. * Clone the current geometry into a new geometry
  39165. * @param id defines the unique ID of the new geometry
  39166. * @returns a new geometry object
  39167. */
  39168. Geometry.prototype.copy = function (id) {
  39169. var vertexData = new BABYLON.VertexData();
  39170. vertexData.indices = [];
  39171. var indices = this.getIndices();
  39172. if (indices) {
  39173. for (var index = 0; index < indices.length; index++) {
  39174. vertexData.indices.push(indices[index]);
  39175. }
  39176. }
  39177. var updatable = false;
  39178. var stopChecking = false;
  39179. var kind;
  39180. for (kind in this._vertexBuffers) {
  39181. // using slice() to make a copy of the array and not just reference it
  39182. var data = this.getVerticesData(kind);
  39183. if (data instanceof Float32Array) {
  39184. vertexData.set(new Float32Array(data), kind);
  39185. }
  39186. else {
  39187. vertexData.set(data.slice(0), kind);
  39188. }
  39189. if (!stopChecking) {
  39190. var vb = this.getVertexBuffer(kind);
  39191. if (vb) {
  39192. updatable = vb.isUpdatable();
  39193. stopChecking = !updatable;
  39194. }
  39195. }
  39196. }
  39197. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39198. geometry.delayLoadState = this.delayLoadState;
  39199. geometry.delayLoadingFile = this.delayLoadingFile;
  39200. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39201. for (kind in this._delayInfo) {
  39202. geometry._delayInfo = geometry._delayInfo || [];
  39203. geometry._delayInfo.push(kind);
  39204. }
  39205. // Bounding info
  39206. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39207. return geometry;
  39208. };
  39209. /**
  39210. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39211. * @return a JSON representation of the current geometry data (without the vertices data)
  39212. */
  39213. Geometry.prototype.serialize = function () {
  39214. var serializationObject = {};
  39215. serializationObject.id = this.id;
  39216. serializationObject.updatable = this._updatable;
  39217. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39218. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39219. }
  39220. return serializationObject;
  39221. };
  39222. Geometry.prototype.toNumberArray = function (origin) {
  39223. if (Array.isArray(origin)) {
  39224. return origin;
  39225. }
  39226. else {
  39227. return Array.prototype.slice.call(origin);
  39228. }
  39229. };
  39230. /**
  39231. * Serialize all vertices data into a JSON oject
  39232. * @returns a JSON representation of the current geometry data
  39233. */
  39234. Geometry.prototype.serializeVerticeData = function () {
  39235. var serializationObject = this.serialize();
  39236. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39237. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39238. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39239. serializationObject.positions._updatable = true;
  39240. }
  39241. }
  39242. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39243. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39244. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39245. serializationObject.normals._updatable = true;
  39246. }
  39247. }
  39248. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39249. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39250. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39251. serializationObject.tangets._updatable = true;
  39252. }
  39253. }
  39254. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39255. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39256. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39257. serializationObject.uvs._updatable = true;
  39258. }
  39259. }
  39260. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39261. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39262. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39263. serializationObject.uv2s._updatable = true;
  39264. }
  39265. }
  39266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39267. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39268. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39269. serializationObject.uv3s._updatable = true;
  39270. }
  39271. }
  39272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39273. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39274. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39275. serializationObject.uv4s._updatable = true;
  39276. }
  39277. }
  39278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39279. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39280. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39281. serializationObject.uv5s._updatable = true;
  39282. }
  39283. }
  39284. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39285. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39286. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39287. serializationObject.uv6s._updatable = true;
  39288. }
  39289. }
  39290. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39291. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39292. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39293. serializationObject.colors._updatable = true;
  39294. }
  39295. }
  39296. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39297. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39298. serializationObject.matricesIndices._isExpanded = true;
  39299. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39300. serializationObject.matricesIndices._updatable = true;
  39301. }
  39302. }
  39303. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39304. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39305. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39306. serializationObject.matricesWeights._updatable = true;
  39307. }
  39308. }
  39309. serializationObject.indices = this.toNumberArray(this.getIndices());
  39310. return serializationObject;
  39311. };
  39312. // Statics
  39313. /**
  39314. * Extracts a clone of a mesh geometry
  39315. * @param mesh defines the source mesh
  39316. * @param id defines the unique ID of the new geometry object
  39317. * @returns the new geometry object
  39318. */
  39319. Geometry.ExtractFromMesh = function (mesh, id) {
  39320. var geometry = mesh._geometry;
  39321. if (!geometry) {
  39322. return null;
  39323. }
  39324. return geometry.copy(id);
  39325. };
  39326. /**
  39327. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39328. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39329. * Be aware Math.random() could cause collisions, but:
  39330. * "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"
  39331. * @returns a string containing a new GUID
  39332. */
  39333. Geometry.RandomId = function () {
  39334. return BABYLON.Tools.RandomId();
  39335. };
  39336. /** @hidden */
  39337. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39338. var scene = mesh.getScene();
  39339. // Geometry
  39340. var geometryId = parsedGeometry.geometryId;
  39341. if (geometryId) {
  39342. var geometry = scene.getGeometryByID(geometryId);
  39343. if (geometry) {
  39344. geometry.applyToMesh(mesh);
  39345. }
  39346. }
  39347. else if (parsedGeometry instanceof ArrayBuffer) {
  39348. var binaryInfo = mesh._binaryInfo;
  39349. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39350. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39351. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39352. }
  39353. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39354. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39355. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39356. }
  39357. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39358. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39359. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39360. }
  39361. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39362. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39363. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39364. }
  39365. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39366. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39367. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39368. }
  39369. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39370. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39371. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39372. }
  39373. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39374. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39375. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39376. }
  39377. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39378. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39379. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39380. }
  39381. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39382. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39384. }
  39385. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39386. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39387. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39388. }
  39389. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39390. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39391. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39392. }
  39393. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39394. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39395. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39396. }
  39397. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39398. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39399. mesh.setIndices(indicesData, null);
  39400. }
  39401. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39402. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39403. mesh.subMeshes = [];
  39404. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39405. var materialIndex = subMeshesData[(i * 5) + 0];
  39406. var verticesStart = subMeshesData[(i * 5) + 1];
  39407. var verticesCount = subMeshesData[(i * 5) + 2];
  39408. var indexStart = subMeshesData[(i * 5) + 3];
  39409. var indexCount = subMeshesData[(i * 5) + 4];
  39410. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39411. }
  39412. }
  39413. }
  39414. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39415. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39416. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39417. if (parsedGeometry.tangents) {
  39418. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39419. }
  39420. if (parsedGeometry.uvs) {
  39421. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39422. }
  39423. if (parsedGeometry.uvs2) {
  39424. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39425. }
  39426. if (parsedGeometry.uvs3) {
  39427. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39428. }
  39429. if (parsedGeometry.uvs4) {
  39430. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39431. }
  39432. if (parsedGeometry.uvs5) {
  39433. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39434. }
  39435. if (parsedGeometry.uvs6) {
  39436. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39437. }
  39438. if (parsedGeometry.colors) {
  39439. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39440. }
  39441. if (parsedGeometry.matricesIndices) {
  39442. if (!parsedGeometry.matricesIndices._isExpanded) {
  39443. var floatIndices = [];
  39444. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39445. var matricesIndex = parsedGeometry.matricesIndices[i];
  39446. floatIndices.push(matricesIndex & 0x000000FF);
  39447. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39448. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39449. floatIndices.push(matricesIndex >> 24);
  39450. }
  39451. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39452. }
  39453. else {
  39454. delete parsedGeometry.matricesIndices._isExpanded;
  39455. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39456. }
  39457. }
  39458. if (parsedGeometry.matricesIndicesExtra) {
  39459. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39460. var floatIndices = [];
  39461. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39462. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39463. floatIndices.push(matricesIndex & 0x000000FF);
  39464. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39465. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39466. floatIndices.push(matricesIndex >> 24);
  39467. }
  39468. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39469. }
  39470. else {
  39471. delete parsedGeometry.matricesIndices._isExpanded;
  39472. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39473. }
  39474. }
  39475. if (parsedGeometry.matricesWeights) {
  39476. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39477. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39478. }
  39479. if (parsedGeometry.matricesWeightsExtra) {
  39480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39481. }
  39482. mesh.setIndices(parsedGeometry.indices, null);
  39483. }
  39484. // SubMeshes
  39485. if (parsedGeometry.subMeshes) {
  39486. mesh.subMeshes = [];
  39487. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39488. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39489. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39490. }
  39491. }
  39492. // Flat shading
  39493. if (mesh._shouldGenerateFlatShading) {
  39494. mesh.convertToFlatShadedMesh();
  39495. delete mesh._shouldGenerateFlatShading;
  39496. }
  39497. // Update
  39498. mesh.computeWorldMatrix(true);
  39499. // Octree
  39500. var sceneOctree = scene.selectionOctree;
  39501. if (sceneOctree !== undefined && sceneOctree !== null) {
  39502. sceneOctree.addMesh(mesh);
  39503. }
  39504. };
  39505. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39506. var epsilon = 1e-3;
  39507. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39508. return;
  39509. }
  39510. var noInfluenceBoneIndex = 0.0;
  39511. if (parsedGeometry.skeletonId > -1) {
  39512. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39513. if (!skeleton) {
  39514. return;
  39515. }
  39516. noInfluenceBoneIndex = skeleton.bones.length;
  39517. }
  39518. else {
  39519. return;
  39520. }
  39521. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39522. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39523. var matricesWeights = parsedGeometry.matricesWeights;
  39524. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39525. var influencers = parsedGeometry.numBoneInfluencer;
  39526. var size = matricesWeights.length;
  39527. for (var i = 0; i < size; i += 4) {
  39528. var weight = 0.0;
  39529. var firstZeroWeight = -1;
  39530. for (var j = 0; j < 4; j++) {
  39531. var w = matricesWeights[i + j];
  39532. weight += w;
  39533. if (w < epsilon && firstZeroWeight < 0) {
  39534. firstZeroWeight = j;
  39535. }
  39536. }
  39537. if (matricesWeightsExtra) {
  39538. for (var j = 0; j < 4; j++) {
  39539. var w = matricesWeightsExtra[i + j];
  39540. weight += w;
  39541. if (w < epsilon && firstZeroWeight < 0) {
  39542. firstZeroWeight = j + 4;
  39543. }
  39544. }
  39545. }
  39546. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39547. firstZeroWeight = influencers - 1;
  39548. }
  39549. if (weight > epsilon) {
  39550. var mweight = 1.0 / weight;
  39551. for (var j = 0; j < 4; j++) {
  39552. matricesWeights[i + j] *= mweight;
  39553. }
  39554. if (matricesWeightsExtra) {
  39555. for (var j = 0; j < 4; j++) {
  39556. matricesWeightsExtra[i + j] *= mweight;
  39557. }
  39558. }
  39559. }
  39560. else {
  39561. if (firstZeroWeight >= 4) {
  39562. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39563. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39564. }
  39565. else {
  39566. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39567. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39568. }
  39569. }
  39570. }
  39571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39572. if (parsedGeometry.matricesWeightsExtra) {
  39573. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39574. }
  39575. };
  39576. /**
  39577. * Create a new geometry from persisted data (Using .babylon file format)
  39578. * @param parsedVertexData defines the persisted data
  39579. * @param scene defines the hosting scene
  39580. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39581. * @returns the new geometry object
  39582. */
  39583. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39584. if (scene.getGeometryByID(parsedVertexData.id)) {
  39585. return null; // null since geometry could be something else than a box...
  39586. }
  39587. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39588. if (BABYLON.Tags) {
  39589. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39590. }
  39591. if (parsedVertexData.delayLoadingFile) {
  39592. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39593. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39594. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39595. geometry._delayInfo = [];
  39596. if (parsedVertexData.hasUVs) {
  39597. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39598. }
  39599. if (parsedVertexData.hasUVs2) {
  39600. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39601. }
  39602. if (parsedVertexData.hasUVs3) {
  39603. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39604. }
  39605. if (parsedVertexData.hasUVs4) {
  39606. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39607. }
  39608. if (parsedVertexData.hasUVs5) {
  39609. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39610. }
  39611. if (parsedVertexData.hasUVs6) {
  39612. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39613. }
  39614. if (parsedVertexData.hasColors) {
  39615. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39616. }
  39617. if (parsedVertexData.hasMatricesIndices) {
  39618. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39619. }
  39620. if (parsedVertexData.hasMatricesWeights) {
  39621. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39622. }
  39623. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39624. }
  39625. else {
  39626. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39627. }
  39628. scene.pushGeometry(geometry, true);
  39629. return geometry;
  39630. };
  39631. return Geometry;
  39632. }());
  39633. BABYLON.Geometry = Geometry;
  39634. // Primitives
  39635. /// Abstract class
  39636. /**
  39637. * Abstract class used to provide common services for all typed geometries
  39638. * @hidden
  39639. */
  39640. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39641. __extends(_PrimitiveGeometry, _super);
  39642. /**
  39643. * Creates a new typed geometry
  39644. * @param id defines the unique ID of the geometry
  39645. * @param scene defines the hosting scene
  39646. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39647. * @param mesh defines the hosting mesh (can be null)
  39648. */
  39649. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39650. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39651. if (mesh === void 0) { mesh = null; }
  39652. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39653. _this._canBeRegenerated = _canBeRegenerated;
  39654. _this._beingRegenerated = true;
  39655. _this.regenerate();
  39656. _this._beingRegenerated = false;
  39657. return _this;
  39658. }
  39659. /**
  39660. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39661. * @returns true if the geometry can be regenerated
  39662. */
  39663. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39664. return this._canBeRegenerated;
  39665. };
  39666. /**
  39667. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39668. */
  39669. _PrimitiveGeometry.prototype.regenerate = function () {
  39670. if (!this._canBeRegenerated) {
  39671. return;
  39672. }
  39673. this._beingRegenerated = true;
  39674. this.setAllVerticesData(this._regenerateVertexData(), false);
  39675. this._beingRegenerated = false;
  39676. };
  39677. /**
  39678. * Clone the geometry
  39679. * @param id defines the unique ID of the new geometry
  39680. * @returns the new geometry
  39681. */
  39682. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39683. return _super.prototype.copy.call(this, id);
  39684. };
  39685. // overrides
  39686. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39687. if (!this._beingRegenerated) {
  39688. return;
  39689. }
  39690. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39691. };
  39692. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39693. if (!this._beingRegenerated) {
  39694. return;
  39695. }
  39696. _super.prototype.setVerticesData.call(this, kind, data, false);
  39697. };
  39698. // to override
  39699. /** @hidden */
  39700. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39701. throw new Error("Abstract method");
  39702. };
  39703. _PrimitiveGeometry.prototype.copy = function (id) {
  39704. throw new Error("Must be overriden in sub-classes.");
  39705. };
  39706. _PrimitiveGeometry.prototype.serialize = function () {
  39707. var serializationObject = _super.prototype.serialize.call(this);
  39708. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39709. return serializationObject;
  39710. };
  39711. return _PrimitiveGeometry;
  39712. }(Geometry));
  39713. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39714. /**
  39715. * Creates a ribbon geometry
  39716. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39717. */
  39718. var RibbonGeometry = /** @class */ (function (_super) {
  39719. __extends(RibbonGeometry, _super);
  39720. /**
  39721. * Creates a ribbon geometry
  39722. * @param id defines the unique ID of the geometry
  39723. * @param scene defines the hosting scene
  39724. * @param pathArray defines the array of paths to use
  39725. * @param closeArray defines if the last path and the first path must be joined
  39726. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39727. * @param offset defines the offset between points
  39728. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39729. * @param mesh defines the hosting mesh (can be null)
  39730. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39731. */
  39732. function RibbonGeometry(id, scene,
  39733. /**
  39734. * Defines the array of paths to use
  39735. */
  39736. pathArray,
  39737. /**
  39738. * Defines if the last and first points of each path in your pathArray must be joined
  39739. */
  39740. closeArray,
  39741. /**
  39742. * Defines if the last and first points of each path in your pathArray must be joined
  39743. */
  39744. closePath,
  39745. /**
  39746. * Defines the offset between points
  39747. */
  39748. offset, canBeRegenerated, mesh,
  39749. /**
  39750. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39751. */
  39752. side) {
  39753. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39754. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39755. _this.pathArray = pathArray;
  39756. _this.closeArray = closeArray;
  39757. _this.closePath = closePath;
  39758. _this.offset = offset;
  39759. _this.side = side;
  39760. return _this;
  39761. }
  39762. /** @hidden */
  39763. RibbonGeometry.prototype._regenerateVertexData = function () {
  39764. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39765. };
  39766. RibbonGeometry.prototype.copy = function (id) {
  39767. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39768. };
  39769. return RibbonGeometry;
  39770. }(_PrimitiveGeometry));
  39771. BABYLON.RibbonGeometry = RibbonGeometry;
  39772. /**
  39773. * Creates a box geometry
  39774. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39775. */
  39776. var BoxGeometry = /** @class */ (function (_super) {
  39777. __extends(BoxGeometry, _super);
  39778. /**
  39779. * Creates a box geometry
  39780. * @param id defines the unique ID of the geometry
  39781. * @param scene defines the hosting scene
  39782. * @param size defines the zise of the box (width, height and depth are the same)
  39783. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39784. * @param mesh defines the hosting mesh (can be null)
  39785. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39786. */
  39787. function BoxGeometry(id, scene,
  39788. /**
  39789. * Defines the zise of the box (width, height and depth are the same)
  39790. */
  39791. size, canBeRegenerated, mesh,
  39792. /**
  39793. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39794. */
  39795. side) {
  39796. if (mesh === void 0) { mesh = null; }
  39797. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39798. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39799. _this.size = size;
  39800. _this.side = side;
  39801. return _this;
  39802. }
  39803. BoxGeometry.prototype._regenerateVertexData = function () {
  39804. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39805. };
  39806. BoxGeometry.prototype.copy = function (id) {
  39807. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39808. };
  39809. BoxGeometry.prototype.serialize = function () {
  39810. var serializationObject = _super.prototype.serialize.call(this);
  39811. serializationObject.size = this.size;
  39812. return serializationObject;
  39813. };
  39814. BoxGeometry.Parse = function (parsedBox, scene) {
  39815. if (scene.getGeometryByID(parsedBox.id)) {
  39816. return null; // null since geometry could be something else than a box...
  39817. }
  39818. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39819. if (BABYLON.Tags) {
  39820. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39821. }
  39822. scene.pushGeometry(box, true);
  39823. return box;
  39824. };
  39825. return BoxGeometry;
  39826. }(_PrimitiveGeometry));
  39827. BABYLON.BoxGeometry = BoxGeometry;
  39828. /**
  39829. * Creates a sphere geometry
  39830. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39831. */
  39832. var SphereGeometry = /** @class */ (function (_super) {
  39833. __extends(SphereGeometry, _super);
  39834. /**
  39835. * Create a new sphere geometry
  39836. * @param id defines the unique ID of the geometry
  39837. * @param scene defines the hosting scene
  39838. * @param segments defines the number of segments to use to create the sphere
  39839. * @param diameter defines the diameter of the sphere
  39840. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39841. * @param mesh defines the hosting mesh (can be null)
  39842. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39843. */
  39844. function SphereGeometry(id, scene,
  39845. /**
  39846. * Defines the number of segments to use to create the sphere
  39847. */
  39848. segments,
  39849. /**
  39850. * Defines the diameter of the sphere
  39851. */
  39852. diameter, canBeRegenerated, mesh,
  39853. /**
  39854. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39855. */
  39856. side) {
  39857. if (mesh === void 0) { mesh = null; }
  39858. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39859. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39860. _this.segments = segments;
  39861. _this.diameter = diameter;
  39862. _this.side = side;
  39863. return _this;
  39864. }
  39865. SphereGeometry.prototype._regenerateVertexData = function () {
  39866. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39867. };
  39868. SphereGeometry.prototype.copy = function (id) {
  39869. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39870. };
  39871. SphereGeometry.prototype.serialize = function () {
  39872. var serializationObject = _super.prototype.serialize.call(this);
  39873. serializationObject.segments = this.segments;
  39874. serializationObject.diameter = this.diameter;
  39875. return serializationObject;
  39876. };
  39877. SphereGeometry.Parse = function (parsedSphere, scene) {
  39878. if (scene.getGeometryByID(parsedSphere.id)) {
  39879. return null; // null since geometry could be something else than a sphere...
  39880. }
  39881. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39882. if (BABYLON.Tags) {
  39883. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39884. }
  39885. scene.pushGeometry(sphere, true);
  39886. return sphere;
  39887. };
  39888. return SphereGeometry;
  39889. }(_PrimitiveGeometry));
  39890. BABYLON.SphereGeometry = SphereGeometry;
  39891. /**
  39892. * Creates a disc geometry
  39893. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39894. */
  39895. var DiscGeometry = /** @class */ (function (_super) {
  39896. __extends(DiscGeometry, _super);
  39897. /**
  39898. * Creates a new disc geometry
  39899. * @param id defines the unique ID of the geometry
  39900. * @param scene defines the hosting scene
  39901. * @param radius defines the radius of the disc
  39902. * @param tessellation defines the tesselation factor to apply to the disc
  39903. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39904. * @param mesh defines the hosting mesh (can be null)
  39905. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39906. */
  39907. function DiscGeometry(id, scene,
  39908. /**
  39909. * Defines the radius of the disc
  39910. */
  39911. radius,
  39912. /**
  39913. * Defines the tesselation factor to apply to the disc
  39914. */
  39915. tessellation, canBeRegenerated, mesh,
  39916. /**
  39917. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39918. */
  39919. side) {
  39920. if (mesh === void 0) { mesh = null; }
  39921. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39922. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39923. _this.radius = radius;
  39924. _this.tessellation = tessellation;
  39925. _this.side = side;
  39926. return _this;
  39927. }
  39928. DiscGeometry.prototype._regenerateVertexData = function () {
  39929. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39930. };
  39931. DiscGeometry.prototype.copy = function (id) {
  39932. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39933. };
  39934. return DiscGeometry;
  39935. }(_PrimitiveGeometry));
  39936. BABYLON.DiscGeometry = DiscGeometry;
  39937. /**
  39938. * Creates a new cylinder geometry
  39939. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39940. */
  39941. var CylinderGeometry = /** @class */ (function (_super) {
  39942. __extends(CylinderGeometry, _super);
  39943. /**
  39944. * Creates a new cylinder geometry
  39945. * @param id defines the unique ID of the geometry
  39946. * @param scene defines the hosting scene
  39947. * @param height defines the height of the cylinder
  39948. * @param diameterTop defines the diameter of the cylinder's top cap
  39949. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39950. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39951. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39952. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39953. * @param mesh defines the hosting mesh (can be null)
  39954. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39955. */
  39956. function CylinderGeometry(id, scene,
  39957. /**
  39958. * Defines the height of the cylinder
  39959. */
  39960. height,
  39961. /**
  39962. * Defines the diameter of the cylinder's top cap
  39963. */
  39964. diameterTop,
  39965. /**
  39966. * Defines the diameter of the cylinder's bottom cap
  39967. */
  39968. diameterBottom,
  39969. /**
  39970. * Defines the tessellation factor to apply to the cylinder
  39971. */
  39972. tessellation,
  39973. /**
  39974. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39975. */
  39976. subdivisions, canBeRegenerated, mesh,
  39977. /**
  39978. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39979. */
  39980. side) {
  39981. if (subdivisions === void 0) { subdivisions = 1; }
  39982. if (mesh === void 0) { mesh = null; }
  39983. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39984. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39985. _this.height = height;
  39986. _this.diameterTop = diameterTop;
  39987. _this.diameterBottom = diameterBottom;
  39988. _this.tessellation = tessellation;
  39989. _this.subdivisions = subdivisions;
  39990. _this.side = side;
  39991. return _this;
  39992. }
  39993. CylinderGeometry.prototype._regenerateVertexData = function () {
  39994. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39995. };
  39996. CylinderGeometry.prototype.copy = function (id) {
  39997. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39998. };
  39999. CylinderGeometry.prototype.serialize = function () {
  40000. var serializationObject = _super.prototype.serialize.call(this);
  40001. serializationObject.height = this.height;
  40002. serializationObject.diameterTop = this.diameterTop;
  40003. serializationObject.diameterBottom = this.diameterBottom;
  40004. serializationObject.tessellation = this.tessellation;
  40005. return serializationObject;
  40006. };
  40007. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40008. if (scene.getGeometryByID(parsedCylinder.id)) {
  40009. return null; // null since geometry could be something else than a cylinder...
  40010. }
  40011. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40012. if (BABYLON.Tags) {
  40013. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40014. }
  40015. scene.pushGeometry(cylinder, true);
  40016. return cylinder;
  40017. };
  40018. return CylinderGeometry;
  40019. }(_PrimitiveGeometry));
  40020. BABYLON.CylinderGeometry = CylinderGeometry;
  40021. /**
  40022. * Creates a new torus geometry
  40023. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40024. */
  40025. var TorusGeometry = /** @class */ (function (_super) {
  40026. __extends(TorusGeometry, _super);
  40027. /**
  40028. * Creates a new torus geometry
  40029. * @param id defines the unique ID of the geometry
  40030. * @param scene defines the hosting scene
  40031. * @param diameter defines the diameter of the torus
  40032. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40033. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40034. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40035. * @param mesh defines the hosting mesh (can be null)
  40036. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40037. */
  40038. function TorusGeometry(id, scene,
  40039. /**
  40040. * Defines the diameter of the torus
  40041. */
  40042. diameter,
  40043. /**
  40044. * Defines the thickness of the torus (ie. internal diameter)
  40045. */
  40046. thickness,
  40047. /**
  40048. * Defines the tesselation factor to apply to the torus
  40049. */
  40050. tessellation, canBeRegenerated, mesh,
  40051. /**
  40052. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40053. */
  40054. side) {
  40055. if (mesh === void 0) { mesh = null; }
  40056. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40057. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40058. _this.diameter = diameter;
  40059. _this.thickness = thickness;
  40060. _this.tessellation = tessellation;
  40061. _this.side = side;
  40062. return _this;
  40063. }
  40064. TorusGeometry.prototype._regenerateVertexData = function () {
  40065. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40066. };
  40067. TorusGeometry.prototype.copy = function (id) {
  40068. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40069. };
  40070. TorusGeometry.prototype.serialize = function () {
  40071. var serializationObject = _super.prototype.serialize.call(this);
  40072. serializationObject.diameter = this.diameter;
  40073. serializationObject.thickness = this.thickness;
  40074. serializationObject.tessellation = this.tessellation;
  40075. return serializationObject;
  40076. };
  40077. TorusGeometry.Parse = function (parsedTorus, scene) {
  40078. if (scene.getGeometryByID(parsedTorus.id)) {
  40079. return null; // null since geometry could be something else than a torus...
  40080. }
  40081. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40082. if (BABYLON.Tags) {
  40083. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40084. }
  40085. scene.pushGeometry(torus, true);
  40086. return torus;
  40087. };
  40088. return TorusGeometry;
  40089. }(_PrimitiveGeometry));
  40090. BABYLON.TorusGeometry = TorusGeometry;
  40091. /**
  40092. * Creates a new ground geometry
  40093. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40094. */
  40095. var GroundGeometry = /** @class */ (function (_super) {
  40096. __extends(GroundGeometry, _super);
  40097. /**
  40098. * Creates a new ground geometry
  40099. * @param id defines the unique ID of the geometry
  40100. * @param scene defines the hosting scene
  40101. * @param width defines the width of the ground
  40102. * @param height defines the height of the ground
  40103. * @param subdivisions defines the subdivisions to apply to the ground
  40104. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40105. * @param mesh defines the hosting mesh (can be null)
  40106. */
  40107. function GroundGeometry(id, scene,
  40108. /**
  40109. * Defines the width of the ground
  40110. */
  40111. width,
  40112. /**
  40113. * Defines the height of the ground
  40114. */
  40115. height,
  40116. /**
  40117. * Defines the subdivisions to apply to the ground
  40118. */
  40119. subdivisions, canBeRegenerated, mesh) {
  40120. if (mesh === void 0) { mesh = null; }
  40121. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40122. _this.width = width;
  40123. _this.height = height;
  40124. _this.subdivisions = subdivisions;
  40125. return _this;
  40126. }
  40127. GroundGeometry.prototype._regenerateVertexData = function () {
  40128. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40129. };
  40130. GroundGeometry.prototype.copy = function (id) {
  40131. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40132. };
  40133. GroundGeometry.prototype.serialize = function () {
  40134. var serializationObject = _super.prototype.serialize.call(this);
  40135. serializationObject.width = this.width;
  40136. serializationObject.height = this.height;
  40137. serializationObject.subdivisions = this.subdivisions;
  40138. return serializationObject;
  40139. };
  40140. GroundGeometry.Parse = function (parsedGround, scene) {
  40141. if (scene.getGeometryByID(parsedGround.id)) {
  40142. return null; // null since geometry could be something else than a ground...
  40143. }
  40144. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40145. if (BABYLON.Tags) {
  40146. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40147. }
  40148. scene.pushGeometry(ground, true);
  40149. return ground;
  40150. };
  40151. return GroundGeometry;
  40152. }(_PrimitiveGeometry));
  40153. BABYLON.GroundGeometry = GroundGeometry;
  40154. /**
  40155. * Creates a tiled ground geometry
  40156. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40157. */
  40158. var TiledGroundGeometry = /** @class */ (function (_super) {
  40159. __extends(TiledGroundGeometry, _super);
  40160. /**
  40161. * Creates a tiled ground geometry
  40162. * @param id defines the unique ID of the geometry
  40163. * @param scene defines the hosting scene
  40164. * @param xmin defines the minimum value on X axis
  40165. * @param zmin defines the minimum value on Z axis
  40166. * @param xmax defines the maximum value on X axis
  40167. * @param zmax defines the maximum value on Z axis
  40168. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40169. * @param precision defines the precision to use when computing the tiles
  40170. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40171. * @param mesh defines the hosting mesh (can be null)
  40172. */
  40173. function TiledGroundGeometry(id, scene,
  40174. /**
  40175. * Defines the minimum value on X axis
  40176. */
  40177. xmin,
  40178. /**
  40179. * Defines the minimum value on Z axis
  40180. */
  40181. zmin,
  40182. /**
  40183. * Defines the maximum value on X axis
  40184. */
  40185. xmax,
  40186. /**
  40187. * Defines the maximum value on Z axis
  40188. */
  40189. zmax,
  40190. /**
  40191. * Defines the subdivisions to apply to the ground
  40192. */
  40193. subdivisions,
  40194. /**
  40195. * Defines the precision to use when computing the tiles
  40196. */
  40197. precision, canBeRegenerated, mesh) {
  40198. if (mesh === void 0) { mesh = null; }
  40199. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40200. _this.xmin = xmin;
  40201. _this.zmin = zmin;
  40202. _this.xmax = xmax;
  40203. _this.zmax = zmax;
  40204. _this.subdivisions = subdivisions;
  40205. _this.precision = precision;
  40206. return _this;
  40207. }
  40208. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40209. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40210. };
  40211. TiledGroundGeometry.prototype.copy = function (id) {
  40212. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40213. };
  40214. return TiledGroundGeometry;
  40215. }(_PrimitiveGeometry));
  40216. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40217. /**
  40218. * Creates a plane geometry
  40219. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40220. */
  40221. var PlaneGeometry = /** @class */ (function (_super) {
  40222. __extends(PlaneGeometry, _super);
  40223. /**
  40224. * Creates a plane geometry
  40225. * @param id defines the unique ID of the geometry
  40226. * @param scene defines the hosting scene
  40227. * @param size defines the size of the plane (width === height)
  40228. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40229. * @param mesh defines the hosting mesh (can be null)
  40230. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40231. */
  40232. function PlaneGeometry(id, scene,
  40233. /**
  40234. * Defines the size of the plane (width === height)
  40235. */
  40236. size, canBeRegenerated, mesh,
  40237. /**
  40238. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40239. */
  40240. side) {
  40241. if (mesh === void 0) { mesh = null; }
  40242. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40243. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40244. _this.size = size;
  40245. _this.side = side;
  40246. return _this;
  40247. }
  40248. PlaneGeometry.prototype._regenerateVertexData = function () {
  40249. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40250. };
  40251. PlaneGeometry.prototype.copy = function (id) {
  40252. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40253. };
  40254. PlaneGeometry.prototype.serialize = function () {
  40255. var serializationObject = _super.prototype.serialize.call(this);
  40256. serializationObject.size = this.size;
  40257. return serializationObject;
  40258. };
  40259. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40260. if (scene.getGeometryByID(parsedPlane.id)) {
  40261. return null; // null since geometry could be something else than a ground...
  40262. }
  40263. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40264. if (BABYLON.Tags) {
  40265. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40266. }
  40267. scene.pushGeometry(plane, true);
  40268. return plane;
  40269. };
  40270. return PlaneGeometry;
  40271. }(_PrimitiveGeometry));
  40272. BABYLON.PlaneGeometry = PlaneGeometry;
  40273. /**
  40274. * Creates a torus knot geometry
  40275. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40276. */
  40277. var TorusKnotGeometry = /** @class */ (function (_super) {
  40278. __extends(TorusKnotGeometry, _super);
  40279. /**
  40280. * Creates a torus knot geometry
  40281. * @param id defines the unique ID of the geometry
  40282. * @param scene defines the hosting scene
  40283. * @param radius defines the radius of the torus knot
  40284. * @param tube defines the thickness of the torus knot tube
  40285. * @param radialSegments defines the number of radial segments
  40286. * @param tubularSegments defines the number of tubular segments
  40287. * @param p defines the first number of windings
  40288. * @param q defines the second number of windings
  40289. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40290. * @param mesh defines the hosting mesh (can be null)
  40291. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40292. */
  40293. function TorusKnotGeometry(id, scene,
  40294. /**
  40295. * Defines the radius of the torus knot
  40296. */
  40297. radius,
  40298. /**
  40299. * Defines the thickness of the torus knot tube
  40300. */
  40301. tube,
  40302. /**
  40303. * Defines the number of radial segments
  40304. */
  40305. radialSegments,
  40306. /**
  40307. * Defines the number of tubular segments
  40308. */
  40309. tubularSegments,
  40310. /**
  40311. * Defines the first number of windings
  40312. */
  40313. p,
  40314. /**
  40315. * Defines the second number of windings
  40316. */
  40317. q, canBeRegenerated, mesh,
  40318. /**
  40319. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40320. */
  40321. side) {
  40322. if (mesh === void 0) { mesh = null; }
  40323. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40324. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40325. _this.radius = radius;
  40326. _this.tube = tube;
  40327. _this.radialSegments = radialSegments;
  40328. _this.tubularSegments = tubularSegments;
  40329. _this.p = p;
  40330. _this.q = q;
  40331. _this.side = side;
  40332. return _this;
  40333. }
  40334. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40335. 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 });
  40336. };
  40337. TorusKnotGeometry.prototype.copy = function (id) {
  40338. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40339. };
  40340. TorusKnotGeometry.prototype.serialize = function () {
  40341. var serializationObject = _super.prototype.serialize.call(this);
  40342. serializationObject.radius = this.radius;
  40343. serializationObject.tube = this.tube;
  40344. serializationObject.radialSegments = this.radialSegments;
  40345. serializationObject.tubularSegments = this.tubularSegments;
  40346. serializationObject.p = this.p;
  40347. serializationObject.q = this.q;
  40348. return serializationObject;
  40349. };
  40350. ;
  40351. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40352. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40353. return null; // null since geometry could be something else than a ground...
  40354. }
  40355. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40356. if (BABYLON.Tags) {
  40357. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40358. }
  40359. scene.pushGeometry(torusKnot, true);
  40360. return torusKnot;
  40361. };
  40362. return TorusKnotGeometry;
  40363. }(_PrimitiveGeometry));
  40364. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40365. //}
  40366. })(BABYLON || (BABYLON = {}));
  40367. //# sourceMappingURL=babylon.geometry.js.map
  40368. var BABYLON;
  40369. (function (BABYLON) {
  40370. /**
  40371. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40372. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40373. */
  40374. var PostProcessManager = /** @class */ (function () {
  40375. /**
  40376. * Creates a new instance PostProcess
  40377. * @param scene The scene that the post process is associated with.
  40378. */
  40379. function PostProcessManager(scene) {
  40380. this._vertexBuffers = {};
  40381. this._scene = scene;
  40382. }
  40383. PostProcessManager.prototype._prepareBuffers = function () {
  40384. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40385. return;
  40386. }
  40387. // VBO
  40388. var vertices = [];
  40389. vertices.push(1, 1);
  40390. vertices.push(-1, 1);
  40391. vertices.push(-1, -1);
  40392. vertices.push(1, -1);
  40393. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40394. this._buildIndexBuffer();
  40395. };
  40396. PostProcessManager.prototype._buildIndexBuffer = function () {
  40397. // Indices
  40398. var indices = [];
  40399. indices.push(0);
  40400. indices.push(1);
  40401. indices.push(2);
  40402. indices.push(0);
  40403. indices.push(2);
  40404. indices.push(3);
  40405. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40406. };
  40407. /**
  40408. * Rebuilds the vertex buffers of the manager.
  40409. */
  40410. PostProcessManager.prototype._rebuild = function () {
  40411. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40412. if (!vb) {
  40413. return;
  40414. }
  40415. vb._rebuild();
  40416. this._buildIndexBuffer();
  40417. };
  40418. // Methods
  40419. /**
  40420. * Prepares a frame to be run through a post process.
  40421. * @param sourceTexture The input texture to the post procesess. (default: null)
  40422. * @param postProcesses An array of post processes to be run. (default: null)
  40423. * @returns True if the post processes were able to be run.
  40424. */
  40425. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40426. if (sourceTexture === void 0) { sourceTexture = null; }
  40427. if (postProcesses === void 0) { postProcesses = null; }
  40428. var camera = this._scene.activeCamera;
  40429. if (!camera) {
  40430. return false;
  40431. }
  40432. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40433. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40434. return false;
  40435. }
  40436. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40437. return true;
  40438. };
  40439. /**
  40440. * Manually render a set of post processes to a texture.
  40441. * @param postProcesses An array of post processes to be run.
  40442. * @param targetTexture The target texture to render to.
  40443. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40444. */
  40445. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40446. if (targetTexture === void 0) { targetTexture = null; }
  40447. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40448. var engine = this._scene.getEngine();
  40449. for (var index = 0; index < postProcesses.length; index++) {
  40450. if (index < postProcesses.length - 1) {
  40451. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40452. }
  40453. else {
  40454. if (targetTexture) {
  40455. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40456. }
  40457. else {
  40458. engine.restoreDefaultFramebuffer();
  40459. }
  40460. }
  40461. var pp = postProcesses[index];
  40462. var effect = pp.apply();
  40463. if (effect) {
  40464. pp.onBeforeRenderObservable.notifyObservers(effect);
  40465. // VBOs
  40466. this._prepareBuffers();
  40467. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40468. // Draw order
  40469. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40470. pp.onAfterRenderObservable.notifyObservers(effect);
  40471. }
  40472. }
  40473. // Restore depth buffer
  40474. engine.setDepthBuffer(true);
  40475. engine.setDepthWrite(true);
  40476. };
  40477. /**
  40478. * Finalize the result of the output of the postprocesses.
  40479. * @param doNotPresent If true the result will not be displayed to the screen.
  40480. * @param targetTexture The target texture to render to.
  40481. * @param faceIndex The index of the face to bind the target texture to.
  40482. * @param postProcesses The array of post processes to render.
  40483. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40484. */
  40485. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40486. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40487. var camera = this._scene.activeCamera;
  40488. if (!camera) {
  40489. return;
  40490. }
  40491. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40492. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40493. return;
  40494. }
  40495. var engine = this._scene.getEngine();
  40496. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40497. var pp = postProcesses[index];
  40498. if (index < len - 1) {
  40499. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40500. }
  40501. else {
  40502. if (targetTexture) {
  40503. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40504. pp._outputTexture = targetTexture;
  40505. }
  40506. else {
  40507. engine.restoreDefaultFramebuffer();
  40508. pp._outputTexture = null;
  40509. }
  40510. }
  40511. if (doNotPresent) {
  40512. break;
  40513. }
  40514. var effect = pp.apply();
  40515. if (effect) {
  40516. pp.onBeforeRenderObservable.notifyObservers(effect);
  40517. // VBOs
  40518. this._prepareBuffers();
  40519. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40520. // Draw order
  40521. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40522. pp.onAfterRenderObservable.notifyObservers(effect);
  40523. }
  40524. }
  40525. // Restore states
  40526. engine.setDepthBuffer(true);
  40527. engine.setDepthWrite(true);
  40528. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40529. };
  40530. /**
  40531. * Disposes of the post process manager.
  40532. */
  40533. PostProcessManager.prototype.dispose = function () {
  40534. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40535. if (buffer) {
  40536. buffer.dispose();
  40537. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40538. }
  40539. if (this._indexBuffer) {
  40540. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40541. this._indexBuffer = null;
  40542. }
  40543. };
  40544. return PostProcessManager;
  40545. }());
  40546. BABYLON.PostProcessManager = PostProcessManager;
  40547. })(BABYLON || (BABYLON = {}));
  40548. //# sourceMappingURL=babylon.postProcessManager.js.map
  40549. var BABYLON;
  40550. (function (BABYLON) {
  40551. /**
  40552. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40553. */
  40554. var PerformanceMonitor = /** @class */ (function () {
  40555. /**
  40556. * constructor
  40557. * @param frameSampleSize The number of samples required to saturate the sliding window
  40558. */
  40559. function PerformanceMonitor(frameSampleSize) {
  40560. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40561. this._enabled = true;
  40562. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40563. }
  40564. /**
  40565. * Samples current frame
  40566. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40567. */
  40568. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40569. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40570. if (!this._enabled)
  40571. return;
  40572. if (this._lastFrameTimeMs != null) {
  40573. var dt = timeMs - this._lastFrameTimeMs;
  40574. this._rollingFrameTime.add(dt);
  40575. }
  40576. this._lastFrameTimeMs = timeMs;
  40577. };
  40578. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40579. /**
  40580. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40581. * @return Average frame time in milliseconds
  40582. */
  40583. get: function () {
  40584. return this._rollingFrameTime.average;
  40585. },
  40586. enumerable: true,
  40587. configurable: true
  40588. });
  40589. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40590. /**
  40591. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40592. * @return Frame time variance in milliseconds squared
  40593. */
  40594. get: function () {
  40595. return this._rollingFrameTime.variance;
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40601. /**
  40602. * Returns the frame time of the most recent frame
  40603. * @return Frame time in milliseconds
  40604. */
  40605. get: function () {
  40606. return this._rollingFrameTime.history(0);
  40607. },
  40608. enumerable: true,
  40609. configurable: true
  40610. });
  40611. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40612. /**
  40613. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40614. * @return Framerate in frames per second
  40615. */
  40616. get: function () {
  40617. return 1000.0 / this._rollingFrameTime.average;
  40618. },
  40619. enumerable: true,
  40620. configurable: true
  40621. });
  40622. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40623. /**
  40624. * Returns the average framerate in frames per second using the most recent frame time
  40625. * @return Framerate in frames per second
  40626. */
  40627. get: function () {
  40628. var history = this._rollingFrameTime.history(0);
  40629. if (history === 0) {
  40630. return 0;
  40631. }
  40632. return 1000.0 / history;
  40633. },
  40634. enumerable: true,
  40635. configurable: true
  40636. });
  40637. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40638. /**
  40639. * Returns true if enough samples have been taken to completely fill the sliding window
  40640. * @return true if saturated
  40641. */
  40642. get: function () {
  40643. return this._rollingFrameTime.isSaturated();
  40644. },
  40645. enumerable: true,
  40646. configurable: true
  40647. });
  40648. /**
  40649. * Enables contributions to the sliding window sample set
  40650. */
  40651. PerformanceMonitor.prototype.enable = function () {
  40652. this._enabled = true;
  40653. };
  40654. /**
  40655. * Disables contributions to the sliding window sample set
  40656. * Samples will not be interpolated over the disabled period
  40657. */
  40658. PerformanceMonitor.prototype.disable = function () {
  40659. this._enabled = false;
  40660. //clear last sample to avoid interpolating over the disabled period when next enabled
  40661. this._lastFrameTimeMs = null;
  40662. };
  40663. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40664. /**
  40665. * Returns true if sampling is enabled
  40666. * @return true if enabled
  40667. */
  40668. get: function () {
  40669. return this._enabled;
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. /**
  40675. * Resets performance monitor
  40676. */
  40677. PerformanceMonitor.prototype.reset = function () {
  40678. //clear last sample to avoid interpolating over the disabled period when next enabled
  40679. this._lastFrameTimeMs = null;
  40680. //wipe record
  40681. this._rollingFrameTime.reset();
  40682. };
  40683. return PerformanceMonitor;
  40684. }());
  40685. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40686. /**
  40687. * RollingAverage
  40688. *
  40689. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40690. */
  40691. var RollingAverage = /** @class */ (function () {
  40692. /**
  40693. * constructor
  40694. * @param length The number of samples required to saturate the sliding window
  40695. */
  40696. function RollingAverage(length) {
  40697. this._samples = new Array(length);
  40698. this.reset();
  40699. }
  40700. /**
  40701. * Adds a sample to the sample set
  40702. * @param v The sample value
  40703. */
  40704. RollingAverage.prototype.add = function (v) {
  40705. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40706. var delta;
  40707. //we need to check if we've already wrapped round
  40708. if (this.isSaturated()) {
  40709. //remove bottom of stack from mean
  40710. var bottomValue = this._samples[this._pos];
  40711. delta = bottomValue - this.average;
  40712. this.average -= delta / (this._sampleCount - 1);
  40713. this._m2 -= delta * (bottomValue - this.average);
  40714. }
  40715. else {
  40716. this._sampleCount++;
  40717. }
  40718. //add new value to mean
  40719. delta = v - this.average;
  40720. this.average += delta / (this._sampleCount);
  40721. this._m2 += delta * (v - this.average);
  40722. //set the new variance
  40723. this.variance = this._m2 / (this._sampleCount - 1);
  40724. this._samples[this._pos] = v;
  40725. this._pos++;
  40726. this._pos %= this._samples.length; //positive wrap around
  40727. };
  40728. /**
  40729. * Returns previously added values or null if outside of history or outside the sliding window domain
  40730. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40731. * @return Value previously recorded with add() or null if outside of range
  40732. */
  40733. RollingAverage.prototype.history = function (i) {
  40734. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40735. return 0;
  40736. }
  40737. var i0 = this._wrapPosition(this._pos - 1.0);
  40738. return this._samples[this._wrapPosition(i0 - i)];
  40739. };
  40740. /**
  40741. * Returns true if enough samples have been taken to completely fill the sliding window
  40742. * @return true if sample-set saturated
  40743. */
  40744. RollingAverage.prototype.isSaturated = function () {
  40745. return this._sampleCount >= this._samples.length;
  40746. };
  40747. /**
  40748. * Resets the rolling average (equivalent to 0 samples taken so far)
  40749. */
  40750. RollingAverage.prototype.reset = function () {
  40751. this.average = 0;
  40752. this.variance = 0;
  40753. this._sampleCount = 0;
  40754. this._pos = 0;
  40755. this._m2 = 0;
  40756. };
  40757. /**
  40758. * Wraps a value around the sample range boundaries
  40759. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40760. * @return Wrapped position in sample range
  40761. */
  40762. RollingAverage.prototype._wrapPosition = function (i) {
  40763. var max = this._samples.length;
  40764. return ((i % max) + max) % max;
  40765. };
  40766. return RollingAverage;
  40767. }());
  40768. BABYLON.RollingAverage = RollingAverage;
  40769. })(BABYLON || (BABYLON = {}));
  40770. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40771. var BABYLON;
  40772. (function (BABYLON) {
  40773. /**
  40774. * This groups together the common properties used for image processing either in direct forward pass
  40775. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40776. * or not.
  40777. */
  40778. var ImageProcessingConfiguration = /** @class */ (function () {
  40779. function ImageProcessingConfiguration() {
  40780. /**
  40781. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40782. */
  40783. this.colorCurves = new BABYLON.ColorCurves();
  40784. this._colorCurvesEnabled = false;
  40785. this._colorGradingEnabled = false;
  40786. this._colorGradingWithGreenDepth = true;
  40787. this._colorGradingBGR = true;
  40788. this._exposure = 1.0;
  40789. this._toneMappingEnabled = false;
  40790. this._contrast = 1.0;
  40791. /**
  40792. * Vignette stretch size.
  40793. */
  40794. this.vignetteStretch = 0;
  40795. /**
  40796. * Vignette centre X Offset.
  40797. */
  40798. this.vignetteCentreX = 0;
  40799. /**
  40800. * Vignette centre Y Offset.
  40801. */
  40802. this.vignetteCentreY = 0;
  40803. /**
  40804. * Vignette weight or intensity of the vignette effect.
  40805. */
  40806. this.vignetteWeight = 1.5;
  40807. /**
  40808. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40809. * if vignetteEnabled is set to true.
  40810. */
  40811. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40812. /**
  40813. * Camera field of view used by the Vignette effect.
  40814. */
  40815. this.vignetteCameraFov = 0.5;
  40816. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40817. this._vignetteEnabled = false;
  40818. this._applyByPostProcess = false;
  40819. this._isEnabled = true;
  40820. /**
  40821. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40822. */
  40823. this.onUpdateParameters = new BABYLON.Observable();
  40824. }
  40825. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40826. /**
  40827. * Gets wether the color curves effect is enabled.
  40828. */
  40829. get: function () {
  40830. return this._colorCurvesEnabled;
  40831. },
  40832. /**
  40833. * Sets wether the color curves effect is enabled.
  40834. */
  40835. set: function (value) {
  40836. if (this._colorCurvesEnabled === value) {
  40837. return;
  40838. }
  40839. this._colorCurvesEnabled = value;
  40840. this._updateParameters();
  40841. },
  40842. enumerable: true,
  40843. configurable: true
  40844. });
  40845. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40846. /**
  40847. * Gets wether the color grading effect is enabled.
  40848. */
  40849. get: function () {
  40850. return this._colorGradingEnabled;
  40851. },
  40852. /**
  40853. * Sets wether the color grading effect is enabled.
  40854. */
  40855. set: function (value) {
  40856. if (this._colorGradingEnabled === value) {
  40857. return;
  40858. }
  40859. this._colorGradingEnabled = value;
  40860. this._updateParameters();
  40861. },
  40862. enumerable: true,
  40863. configurable: true
  40864. });
  40865. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40866. /**
  40867. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40868. */
  40869. get: function () {
  40870. return this._colorGradingWithGreenDepth;
  40871. },
  40872. /**
  40873. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40874. */
  40875. set: function (value) {
  40876. if (this._colorGradingWithGreenDepth === value) {
  40877. return;
  40878. }
  40879. this._colorGradingWithGreenDepth = value;
  40880. this._updateParameters();
  40881. },
  40882. enumerable: true,
  40883. configurable: true
  40884. });
  40885. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40886. /**
  40887. * Gets wether the color grading texture contains BGR values.
  40888. */
  40889. get: function () {
  40890. return this._colorGradingBGR;
  40891. },
  40892. /**
  40893. * Sets wether the color grading texture contains BGR values.
  40894. */
  40895. set: function (value) {
  40896. if (this._colorGradingBGR === value) {
  40897. return;
  40898. }
  40899. this._colorGradingBGR = value;
  40900. this._updateParameters();
  40901. },
  40902. enumerable: true,
  40903. configurable: true
  40904. });
  40905. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40906. /**
  40907. * Gets the Exposure used in the effect.
  40908. */
  40909. get: function () {
  40910. return this._exposure;
  40911. },
  40912. /**
  40913. * Sets the Exposure used in the effect.
  40914. */
  40915. set: function (value) {
  40916. if (this._exposure === value) {
  40917. return;
  40918. }
  40919. this._exposure = value;
  40920. this._updateParameters();
  40921. },
  40922. enumerable: true,
  40923. configurable: true
  40924. });
  40925. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40926. /**
  40927. * Gets wether the tone mapping effect is enabled.
  40928. */
  40929. get: function () {
  40930. return this._toneMappingEnabled;
  40931. },
  40932. /**
  40933. * Sets wether the tone mapping effect is enabled.
  40934. */
  40935. set: function (value) {
  40936. if (this._toneMappingEnabled === value) {
  40937. return;
  40938. }
  40939. this._toneMappingEnabled = value;
  40940. this._updateParameters();
  40941. },
  40942. enumerable: true,
  40943. configurable: true
  40944. });
  40945. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40946. /**
  40947. * Gets the contrast used in the effect.
  40948. */
  40949. get: function () {
  40950. return this._contrast;
  40951. },
  40952. /**
  40953. * Sets the contrast used in the effect.
  40954. */
  40955. set: function (value) {
  40956. if (this._contrast === value) {
  40957. return;
  40958. }
  40959. this._contrast = value;
  40960. this._updateParameters();
  40961. },
  40962. enumerable: true,
  40963. configurable: true
  40964. });
  40965. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40966. /**
  40967. * Gets the vignette blend mode allowing different kind of effect.
  40968. */
  40969. get: function () {
  40970. return this._vignetteBlendMode;
  40971. },
  40972. /**
  40973. * Sets the vignette blend mode allowing different kind of effect.
  40974. */
  40975. set: function (value) {
  40976. if (this._vignetteBlendMode === value) {
  40977. return;
  40978. }
  40979. this._vignetteBlendMode = value;
  40980. this._updateParameters();
  40981. },
  40982. enumerable: true,
  40983. configurable: true
  40984. });
  40985. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40986. /**
  40987. * Gets wether the vignette effect is enabled.
  40988. */
  40989. get: function () {
  40990. return this._vignetteEnabled;
  40991. },
  40992. /**
  40993. * Sets wether the vignette effect is enabled.
  40994. */
  40995. set: function (value) {
  40996. if (this._vignetteEnabled === value) {
  40997. return;
  40998. }
  40999. this._vignetteEnabled = value;
  41000. this._updateParameters();
  41001. },
  41002. enumerable: true,
  41003. configurable: true
  41004. });
  41005. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41006. /**
  41007. * Gets wether the image processing is applied through a post process or not.
  41008. */
  41009. get: function () {
  41010. return this._applyByPostProcess;
  41011. },
  41012. /**
  41013. * Sets wether the image processing is applied through a post process or not.
  41014. */
  41015. set: function (value) {
  41016. if (this._applyByPostProcess === value) {
  41017. return;
  41018. }
  41019. this._applyByPostProcess = value;
  41020. this._updateParameters();
  41021. },
  41022. enumerable: true,
  41023. configurable: true
  41024. });
  41025. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41026. /**
  41027. * Gets wether the image processing is enabled or not.
  41028. */
  41029. get: function () {
  41030. return this._isEnabled;
  41031. },
  41032. /**
  41033. * Sets wether the image processing is enabled or not.
  41034. */
  41035. set: function (value) {
  41036. if (this._isEnabled === value) {
  41037. return;
  41038. }
  41039. this._isEnabled = value;
  41040. this._updateParameters();
  41041. },
  41042. enumerable: true,
  41043. configurable: true
  41044. });
  41045. /**
  41046. * Method called each time the image processing information changes requires to recompile the effect.
  41047. */
  41048. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41049. this.onUpdateParameters.notifyObservers(this);
  41050. };
  41051. ImageProcessingConfiguration.prototype.getClassName = function () {
  41052. return "ImageProcessingConfiguration";
  41053. };
  41054. /**
  41055. * Prepare the list of uniforms associated with the Image Processing effects.
  41056. * @param uniformsList The list of uniforms used in the effect
  41057. * @param defines the list of defines currently in use
  41058. */
  41059. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41060. if (defines.EXPOSURE) {
  41061. uniforms.push("exposureLinear");
  41062. }
  41063. if (defines.CONTRAST) {
  41064. uniforms.push("contrast");
  41065. }
  41066. if (defines.COLORGRADING) {
  41067. uniforms.push("colorTransformSettings");
  41068. }
  41069. if (defines.VIGNETTE) {
  41070. uniforms.push("vInverseScreenSize");
  41071. uniforms.push("vignetteSettings1");
  41072. uniforms.push("vignetteSettings2");
  41073. }
  41074. if (defines.COLORCURVES) {
  41075. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41076. }
  41077. };
  41078. /**
  41079. * Prepare the list of samplers associated with the Image Processing effects.
  41080. * @param uniformsList The list of uniforms used in the effect
  41081. * @param defines the list of defines currently in use
  41082. */
  41083. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41084. if (defines.COLORGRADING) {
  41085. samplersList.push("txColorTransform");
  41086. }
  41087. };
  41088. /**
  41089. * Prepare the list of defines associated to the shader.
  41090. * @param defines the list of defines to complete
  41091. */
  41092. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41093. if (forPostProcess === void 0) { forPostProcess = false; }
  41094. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41095. defines.VIGNETTE = false;
  41096. defines.TONEMAPPING = false;
  41097. defines.CONTRAST = false;
  41098. defines.EXPOSURE = false;
  41099. defines.COLORCURVES = false;
  41100. defines.COLORGRADING = false;
  41101. defines.COLORGRADING3D = false;
  41102. defines.IMAGEPROCESSING = false;
  41103. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41104. return;
  41105. }
  41106. defines.VIGNETTE = this.vignetteEnabled;
  41107. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41108. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41109. defines.TONEMAPPING = this.toneMappingEnabled;
  41110. defines.CONTRAST = (this.contrast !== 1.0);
  41111. defines.EXPOSURE = (this.exposure !== 1.0);
  41112. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41113. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41114. if (defines.COLORGRADING) {
  41115. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41116. }
  41117. else {
  41118. defines.COLORGRADING3D = false;
  41119. }
  41120. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41121. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41122. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41123. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41124. };
  41125. /**
  41126. * Returns true if all the image processing information are ready.
  41127. */
  41128. ImageProcessingConfiguration.prototype.isReady = function () {
  41129. // Color Grading texure can not be none blocking.
  41130. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41131. };
  41132. /**
  41133. * Binds the image processing to the shader.
  41134. * @param effect The effect to bind to
  41135. */
  41136. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41137. if (aspectRatio === void 0) { aspectRatio = 1; }
  41138. // Color Curves
  41139. if (this._colorCurvesEnabled && this.colorCurves) {
  41140. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41141. }
  41142. // Vignette
  41143. if (this._vignetteEnabled) {
  41144. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41145. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41146. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41147. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41148. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41149. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41150. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41151. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41152. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41153. var vignettePower = -2.0 * this.vignetteWeight;
  41154. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41155. }
  41156. // Exposure
  41157. effect.setFloat("exposureLinear", this.exposure);
  41158. // Contrast
  41159. effect.setFloat("contrast", this.contrast);
  41160. // Color transform settings
  41161. if (this.colorGradingTexture) {
  41162. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41163. var textureSize = this.colorGradingTexture.getSize().height;
  41164. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41165. 0.5 / textureSize, // textureOffset
  41166. textureSize, // textureSize
  41167. this.colorGradingTexture.level // weight
  41168. );
  41169. }
  41170. };
  41171. /**
  41172. * Clones the current image processing instance.
  41173. * @return The cloned image processing
  41174. */
  41175. ImageProcessingConfiguration.prototype.clone = function () {
  41176. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41177. };
  41178. /**
  41179. * Serializes the current image processing instance to a json representation.
  41180. * @return a JSON representation
  41181. */
  41182. ImageProcessingConfiguration.prototype.serialize = function () {
  41183. return BABYLON.SerializationHelper.Serialize(this);
  41184. };
  41185. /**
  41186. * Parses the image processing from a json representation.
  41187. * @param source the JSON source to parse
  41188. * @return The parsed image processing
  41189. */
  41190. ImageProcessingConfiguration.Parse = function (source) {
  41191. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41192. };
  41193. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41194. /**
  41195. * Used to apply the vignette as a mix with the pixel color.
  41196. */
  41197. get: function () {
  41198. return this._VIGNETTEMODE_MULTIPLY;
  41199. },
  41200. enumerable: true,
  41201. configurable: true
  41202. });
  41203. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41204. /**
  41205. * Used to apply the vignette as a replacement of the pixel color.
  41206. */
  41207. get: function () {
  41208. return this._VIGNETTEMODE_OPAQUE;
  41209. },
  41210. enumerable: true,
  41211. configurable: true
  41212. });
  41213. // Static constants associated to the image processing.
  41214. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41215. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41216. __decorate([
  41217. BABYLON.serializeAsColorCurves()
  41218. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41219. __decorate([
  41220. BABYLON.serialize()
  41221. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41222. __decorate([
  41223. BABYLON.serializeAsTexture()
  41224. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41225. __decorate([
  41226. BABYLON.serialize()
  41227. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41228. __decorate([
  41229. BABYLON.serialize()
  41230. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41231. __decorate([
  41232. BABYLON.serialize()
  41233. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41234. __decorate([
  41235. BABYLON.serialize()
  41236. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41237. __decorate([
  41238. BABYLON.serialize()
  41239. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41240. __decorate([
  41241. BABYLON.serialize()
  41242. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41243. __decorate([
  41244. BABYLON.serialize()
  41245. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41246. __decorate([
  41247. BABYLON.serialize()
  41248. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41249. __decorate([
  41250. BABYLON.serialize()
  41251. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41252. __decorate([
  41253. BABYLON.serialize()
  41254. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41255. __decorate([
  41256. BABYLON.serializeAsColor4()
  41257. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41258. __decorate([
  41259. BABYLON.serialize()
  41260. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41261. __decorate([
  41262. BABYLON.serialize()
  41263. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41264. __decorate([
  41265. BABYLON.serialize()
  41266. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41267. __decorate([
  41268. BABYLON.serialize()
  41269. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41270. __decorate([
  41271. BABYLON.serialize()
  41272. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41273. return ImageProcessingConfiguration;
  41274. }());
  41275. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41276. })(BABYLON || (BABYLON = {}));
  41277. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41278. var BABYLON;
  41279. (function (BABYLON) {
  41280. /**
  41281. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41282. * It can help converting any input color in a desired output one. This can then be used to create effects
  41283. * from sepia, black and white to sixties or futuristic rendering...
  41284. *
  41285. * The only supported format is currently 3dl.
  41286. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41287. */
  41288. var ColorGradingTexture = /** @class */ (function (_super) {
  41289. __extends(ColorGradingTexture, _super);
  41290. /**
  41291. * Instantiates a ColorGradingTexture from the following parameters.
  41292. *
  41293. * @param url The location of the color gradind data (currently only supporting 3dl)
  41294. * @param scene The scene the texture will be used in
  41295. */
  41296. function ColorGradingTexture(url, scene) {
  41297. var _this = _super.call(this, scene) || this;
  41298. if (!url) {
  41299. return _this;
  41300. }
  41301. _this._engine = scene.getEngine();
  41302. _this._textureMatrix = BABYLON.Matrix.Identity();
  41303. _this.name = url;
  41304. _this.url = url;
  41305. _this.hasAlpha = false;
  41306. _this.isCube = false;
  41307. _this.is3D = _this._engine.webGLVersion > 1;
  41308. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41309. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41310. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41311. _this.anisotropicFilteringLevel = 1;
  41312. _this._texture = _this._getFromCache(url, true);
  41313. if (!_this._texture) {
  41314. if (!scene.useDelayedTextureLoading) {
  41315. _this.loadTexture();
  41316. }
  41317. else {
  41318. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41319. }
  41320. }
  41321. return _this;
  41322. }
  41323. /**
  41324. * Returns the texture matrix used in most of the material.
  41325. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41326. */
  41327. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41328. return this._textureMatrix;
  41329. };
  41330. /**
  41331. * Occurs when the file being loaded is a .3dl LUT file.
  41332. */
  41333. ColorGradingTexture.prototype.load3dlTexture = function () {
  41334. var engine = this._engine;
  41335. var texture;
  41336. if (engine.webGLVersion === 1) {
  41337. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41338. }
  41339. else {
  41340. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41341. }
  41342. this._texture = texture;
  41343. var callback = function (text) {
  41344. if (typeof text !== "string") {
  41345. return;
  41346. }
  41347. var data = null;
  41348. var tempData = null;
  41349. var line;
  41350. var lines = text.split('\n');
  41351. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41352. var maxColor = 0;
  41353. for (var i = 0; i < lines.length; i++) {
  41354. line = lines[i];
  41355. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41356. continue;
  41357. if (line.indexOf('#') === 0)
  41358. continue;
  41359. var words = line.split(" ");
  41360. if (size === 0) {
  41361. // Number of space + one
  41362. size = words.length;
  41363. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41364. tempData = new Float32Array(size * size * size * 4);
  41365. continue;
  41366. }
  41367. if (size != 0) {
  41368. var r = Math.max(parseInt(words[0]), 0);
  41369. var g = Math.max(parseInt(words[1]), 0);
  41370. var b = Math.max(parseInt(words[2]), 0);
  41371. maxColor = Math.max(r, maxColor);
  41372. maxColor = Math.max(g, maxColor);
  41373. maxColor = Math.max(b, maxColor);
  41374. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41375. if (tempData) {
  41376. tempData[pixelStorageIndex + 0] = r;
  41377. tempData[pixelStorageIndex + 1] = g;
  41378. tempData[pixelStorageIndex + 2] = b;
  41379. }
  41380. pixelIndexSlice++;
  41381. if (pixelIndexSlice % size == 0) {
  41382. pixelIndexH++;
  41383. pixelIndexSlice = 0;
  41384. if (pixelIndexH % size == 0) {
  41385. pixelIndexW++;
  41386. pixelIndexH = 0;
  41387. }
  41388. }
  41389. }
  41390. }
  41391. if (tempData && data) {
  41392. for (var i = 0; i < tempData.length; i++) {
  41393. if (i > 0 && (i + 1) % 4 === 0) {
  41394. data[i] = 255;
  41395. }
  41396. else {
  41397. var value = tempData[i];
  41398. data[i] = (value / maxColor * 255);
  41399. }
  41400. }
  41401. }
  41402. if (texture.is3D) {
  41403. texture.updateSize(size, size, size);
  41404. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41405. }
  41406. else {
  41407. texture.updateSize(size * size, size);
  41408. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41409. }
  41410. };
  41411. var scene = this.getScene();
  41412. if (scene) {
  41413. scene._loadFile(this.url, callback);
  41414. }
  41415. else {
  41416. this._engine._loadFile(this.url, callback);
  41417. }
  41418. return this._texture;
  41419. };
  41420. /**
  41421. * Starts the loading process of the texture.
  41422. */
  41423. ColorGradingTexture.prototype.loadTexture = function () {
  41424. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41425. this.load3dlTexture();
  41426. }
  41427. };
  41428. /**
  41429. * Clones the color gradind texture.
  41430. */
  41431. ColorGradingTexture.prototype.clone = function () {
  41432. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41433. // Base texture
  41434. newTexture.level = this.level;
  41435. return newTexture;
  41436. };
  41437. /**
  41438. * Called during delayed load for textures.
  41439. */
  41440. ColorGradingTexture.prototype.delayLoad = function () {
  41441. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41442. return;
  41443. }
  41444. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41445. this._texture = this._getFromCache(this.url, true);
  41446. if (!this._texture) {
  41447. this.loadTexture();
  41448. }
  41449. };
  41450. /**
  41451. * Parses a color grading texture serialized by Babylon.
  41452. * @param parsedTexture The texture information being parsedTexture
  41453. * @param scene The scene to load the texture in
  41454. * @param rootUrl The root url of the data assets to load
  41455. * @return A color gradind texture
  41456. */
  41457. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41458. var texture = null;
  41459. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41460. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41461. texture.name = parsedTexture.name;
  41462. texture.level = parsedTexture.level;
  41463. }
  41464. return texture;
  41465. };
  41466. /**
  41467. * Serializes the LUT texture to json format.
  41468. */
  41469. ColorGradingTexture.prototype.serialize = function () {
  41470. if (!this.name) {
  41471. return null;
  41472. }
  41473. var serializationObject = {};
  41474. serializationObject.name = this.name;
  41475. serializationObject.level = this.level;
  41476. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41477. return serializationObject;
  41478. };
  41479. /**
  41480. * Empty line regex stored for GC.
  41481. */
  41482. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41483. return ColorGradingTexture;
  41484. }(BABYLON.BaseTexture));
  41485. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41486. })(BABYLON || (BABYLON = {}));
  41487. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41488. var BABYLON;
  41489. (function (BABYLON) {
  41490. /**
  41491. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41492. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41493. * 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;
  41494. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41495. */
  41496. var ColorCurves = /** @class */ (function () {
  41497. function ColorCurves() {
  41498. this._dirty = true;
  41499. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41500. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41501. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41502. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41503. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41504. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41505. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41506. this._globalHue = 30;
  41507. this._globalDensity = 0;
  41508. this._globalSaturation = 0;
  41509. this._globalExposure = 0;
  41510. this._highlightsHue = 30;
  41511. this._highlightsDensity = 0;
  41512. this._highlightsSaturation = 0;
  41513. this._highlightsExposure = 0;
  41514. this._midtonesHue = 30;
  41515. this._midtonesDensity = 0;
  41516. this._midtonesSaturation = 0;
  41517. this._midtonesExposure = 0;
  41518. this._shadowsHue = 30;
  41519. this._shadowsDensity = 0;
  41520. this._shadowsSaturation = 0;
  41521. this._shadowsExposure = 0;
  41522. }
  41523. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41524. /**
  41525. * Gets the global Hue value.
  41526. * 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).
  41527. */
  41528. get: function () {
  41529. return this._globalHue;
  41530. },
  41531. /**
  41532. * Sets the global Hue value.
  41533. * 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).
  41534. */
  41535. set: function (value) {
  41536. this._globalHue = value;
  41537. this._dirty = true;
  41538. },
  41539. enumerable: true,
  41540. configurable: true
  41541. });
  41542. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41543. /**
  41544. * Gets the global Density value.
  41545. * 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.
  41546. * Values less than zero provide a filter of opposite hue.
  41547. */
  41548. get: function () {
  41549. return this._globalDensity;
  41550. },
  41551. /**
  41552. * Sets the global Density value.
  41553. * 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.
  41554. * Values less than zero provide a filter of opposite hue.
  41555. */
  41556. set: function (value) {
  41557. this._globalDensity = value;
  41558. this._dirty = true;
  41559. },
  41560. enumerable: true,
  41561. configurable: true
  41562. });
  41563. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41564. /**
  41565. * Gets the global Saturation value.
  41566. * 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.
  41567. */
  41568. get: function () {
  41569. return this._globalSaturation;
  41570. },
  41571. /**
  41572. * Sets the global Saturation value.
  41573. * 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.
  41574. */
  41575. set: function (value) {
  41576. this._globalSaturation = value;
  41577. this._dirty = true;
  41578. },
  41579. enumerable: true,
  41580. configurable: true
  41581. });
  41582. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41583. /**
  41584. * Gets the highlights Hue value.
  41585. * 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).
  41586. */
  41587. get: function () {
  41588. return this._highlightsHue;
  41589. },
  41590. /**
  41591. * Sets the highlights Hue value.
  41592. * 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).
  41593. */
  41594. set: function (value) {
  41595. this._highlightsHue = value;
  41596. this._dirty = true;
  41597. },
  41598. enumerable: true,
  41599. configurable: true
  41600. });
  41601. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41602. /**
  41603. * Gets the highlights Density value.
  41604. * 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.
  41605. * Values less than zero provide a filter of opposite hue.
  41606. */
  41607. get: function () {
  41608. return this._highlightsDensity;
  41609. },
  41610. /**
  41611. * Sets the highlights Density value.
  41612. * 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.
  41613. * Values less than zero provide a filter of opposite hue.
  41614. */
  41615. set: function (value) {
  41616. this._highlightsDensity = value;
  41617. this._dirty = true;
  41618. },
  41619. enumerable: true,
  41620. configurable: true
  41621. });
  41622. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41623. /**
  41624. * Gets the highlights Saturation value.
  41625. * 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.
  41626. */
  41627. get: function () {
  41628. return this._highlightsSaturation;
  41629. },
  41630. /**
  41631. * Sets the highlights Saturation value.
  41632. * 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.
  41633. */
  41634. set: function (value) {
  41635. this._highlightsSaturation = value;
  41636. this._dirty = true;
  41637. },
  41638. enumerable: true,
  41639. configurable: true
  41640. });
  41641. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41642. /**
  41643. * Gets the highlights Exposure value.
  41644. * 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.
  41645. */
  41646. get: function () {
  41647. return this._highlightsExposure;
  41648. },
  41649. /**
  41650. * Sets the highlights Exposure value.
  41651. * 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.
  41652. */
  41653. set: function (value) {
  41654. this._highlightsExposure = value;
  41655. this._dirty = true;
  41656. },
  41657. enumerable: true,
  41658. configurable: true
  41659. });
  41660. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41661. /**
  41662. * Gets the midtones Hue value.
  41663. * 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).
  41664. */
  41665. get: function () {
  41666. return this._midtonesHue;
  41667. },
  41668. /**
  41669. * Sets the midtones Hue value.
  41670. * 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).
  41671. */
  41672. set: function (value) {
  41673. this._midtonesHue = value;
  41674. this._dirty = true;
  41675. },
  41676. enumerable: true,
  41677. configurable: true
  41678. });
  41679. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41680. /**
  41681. * Gets the midtones Density value.
  41682. * 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.
  41683. * Values less than zero provide a filter of opposite hue.
  41684. */
  41685. get: function () {
  41686. return this._midtonesDensity;
  41687. },
  41688. /**
  41689. * Sets the midtones Density value.
  41690. * 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.
  41691. * Values less than zero provide a filter of opposite hue.
  41692. */
  41693. set: function (value) {
  41694. this._midtonesDensity = value;
  41695. this._dirty = true;
  41696. },
  41697. enumerable: true,
  41698. configurable: true
  41699. });
  41700. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41701. /**
  41702. * Gets the midtones Saturation value.
  41703. * 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.
  41704. */
  41705. get: function () {
  41706. return this._midtonesSaturation;
  41707. },
  41708. /**
  41709. * Sets the midtones Saturation value.
  41710. * 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.
  41711. */
  41712. set: function (value) {
  41713. this._midtonesSaturation = value;
  41714. this._dirty = true;
  41715. },
  41716. enumerable: true,
  41717. configurable: true
  41718. });
  41719. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41720. /**
  41721. * Gets the midtones Exposure value.
  41722. * 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.
  41723. */
  41724. get: function () {
  41725. return this._midtonesExposure;
  41726. },
  41727. /**
  41728. * Sets the midtones Exposure value.
  41729. * 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.
  41730. */
  41731. set: function (value) {
  41732. this._midtonesExposure = value;
  41733. this._dirty = true;
  41734. },
  41735. enumerable: true,
  41736. configurable: true
  41737. });
  41738. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41739. /**
  41740. * Gets the shadows Hue value.
  41741. * 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).
  41742. */
  41743. get: function () {
  41744. return this._shadowsHue;
  41745. },
  41746. /**
  41747. * Sets the shadows Hue value.
  41748. * 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).
  41749. */
  41750. set: function (value) {
  41751. this._shadowsHue = value;
  41752. this._dirty = true;
  41753. },
  41754. enumerable: true,
  41755. configurable: true
  41756. });
  41757. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41758. /**
  41759. * Gets the shadows Density value.
  41760. * 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.
  41761. * Values less than zero provide a filter of opposite hue.
  41762. */
  41763. get: function () {
  41764. return this._shadowsDensity;
  41765. },
  41766. /**
  41767. * Sets the shadows Density value.
  41768. * 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.
  41769. * Values less than zero provide a filter of opposite hue.
  41770. */
  41771. set: function (value) {
  41772. this._shadowsDensity = value;
  41773. this._dirty = true;
  41774. },
  41775. enumerable: true,
  41776. configurable: true
  41777. });
  41778. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41779. /**
  41780. * Gets the shadows Saturation value.
  41781. * 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.
  41782. */
  41783. get: function () {
  41784. return this._shadowsSaturation;
  41785. },
  41786. /**
  41787. * Sets the shadows Saturation value.
  41788. * 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.
  41789. */
  41790. set: function (value) {
  41791. this._shadowsSaturation = value;
  41792. this._dirty = true;
  41793. },
  41794. enumerable: true,
  41795. configurable: true
  41796. });
  41797. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41798. /**
  41799. * Gets the shadows Exposure value.
  41800. * 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.
  41801. */
  41802. get: function () {
  41803. return this._shadowsExposure;
  41804. },
  41805. /**
  41806. * Sets the shadows Exposure value.
  41807. * 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.
  41808. */
  41809. set: function (value) {
  41810. this._shadowsExposure = value;
  41811. this._dirty = true;
  41812. },
  41813. enumerable: true,
  41814. configurable: true
  41815. });
  41816. ColorCurves.prototype.getClassName = function () {
  41817. return "ColorCurves";
  41818. };
  41819. /**
  41820. * Binds the color curves to the shader.
  41821. * @param colorCurves The color curve to bind
  41822. * @param effect The effect to bind to
  41823. */
  41824. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41825. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41826. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41827. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41828. if (colorCurves._dirty) {
  41829. colorCurves._dirty = false;
  41830. // Fill in global info.
  41831. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41832. // Compute highlights info.
  41833. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41834. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41835. // Compute midtones info.
  41836. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41837. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41838. // Compute shadows info.
  41839. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41840. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41841. // Compute deltas (neutral is midtones).
  41842. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41843. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41844. }
  41845. if (effect) {
  41846. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41847. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41848. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41849. }
  41850. };
  41851. /**
  41852. * Prepare the list of uniforms associated with the ColorCurves effects.
  41853. * @param uniformsList The list of uniforms used in the effect
  41854. */
  41855. ColorCurves.PrepareUniforms = function (uniformsList) {
  41856. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41857. };
  41858. /**
  41859. * Returns color grading data based on a hue, density, saturation and exposure value.
  41860. * @param filterHue The hue of the color filter.
  41861. * @param filterDensity The density of the color filter.
  41862. * @param saturation The saturation.
  41863. * @param exposure The exposure.
  41864. * @param result The result data container.
  41865. */
  41866. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41867. if (hue == null) {
  41868. return;
  41869. }
  41870. hue = ColorCurves.clamp(hue, 0, 360);
  41871. density = ColorCurves.clamp(density, -100, 100);
  41872. saturation = ColorCurves.clamp(saturation, -100, 100);
  41873. exposure = ColorCurves.clamp(exposure, -100, 100);
  41874. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41875. // so that the maximum filter density is only 50% control. This provides fine control
  41876. // for small values and reasonable range.
  41877. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41878. density *= 0.5;
  41879. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41880. if (density < 0) {
  41881. density *= -1;
  41882. hue = (hue + 180) % 360;
  41883. }
  41884. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41885. result.scaleToRef(2, result);
  41886. result.a = 1 + 0.01 * saturation;
  41887. };
  41888. /**
  41889. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41890. * @param value The input slider value in range [-100,100].
  41891. * @returns Adjusted value.
  41892. */
  41893. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41894. value /= 100;
  41895. var x = Math.abs(value);
  41896. x = Math.pow(x, 2);
  41897. if (value < 0) {
  41898. x *= -1;
  41899. }
  41900. x *= 100;
  41901. return x;
  41902. };
  41903. /**
  41904. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41905. * @param hue The hue (H) input.
  41906. * @param saturation The saturation (S) input.
  41907. * @param brightness The brightness (B) input.
  41908. * @result An RGBA color represented as Vector4.
  41909. */
  41910. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41911. var h = ColorCurves.clamp(hue, 0, 360);
  41912. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41913. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41914. if (s === 0) {
  41915. result.r = v;
  41916. result.g = v;
  41917. result.b = v;
  41918. }
  41919. else {
  41920. // sector 0 to 5
  41921. h /= 60;
  41922. var i = Math.floor(h);
  41923. // fractional part of h
  41924. var f = h - i;
  41925. var p = v * (1 - s);
  41926. var q = v * (1 - s * f);
  41927. var t = v * (1 - s * (1 - f));
  41928. switch (i) {
  41929. case 0:
  41930. result.r = v;
  41931. result.g = t;
  41932. result.b = p;
  41933. break;
  41934. case 1:
  41935. result.r = q;
  41936. result.g = v;
  41937. result.b = p;
  41938. break;
  41939. case 2:
  41940. result.r = p;
  41941. result.g = v;
  41942. result.b = t;
  41943. break;
  41944. case 3:
  41945. result.r = p;
  41946. result.g = q;
  41947. result.b = v;
  41948. break;
  41949. case 4:
  41950. result.r = t;
  41951. result.g = p;
  41952. result.b = v;
  41953. break;
  41954. default: // case 5:
  41955. result.r = v;
  41956. result.g = p;
  41957. result.b = q;
  41958. break;
  41959. }
  41960. }
  41961. result.a = 1;
  41962. };
  41963. /**
  41964. * Returns a value clamped between min and max
  41965. * @param value The value to clamp
  41966. * @param min The minimum of value
  41967. * @param max The maximum of value
  41968. * @returns The clamped value.
  41969. */
  41970. ColorCurves.clamp = function (value, min, max) {
  41971. return Math.min(Math.max(value, min), max);
  41972. };
  41973. /**
  41974. * Clones the current color curve instance.
  41975. * @return The cloned curves
  41976. */
  41977. ColorCurves.prototype.clone = function () {
  41978. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41979. };
  41980. /**
  41981. * Serializes the current color curve instance to a json representation.
  41982. * @return a JSON representation
  41983. */
  41984. ColorCurves.prototype.serialize = function () {
  41985. return BABYLON.SerializationHelper.Serialize(this);
  41986. };
  41987. /**
  41988. * Parses the color curve from a json representation.
  41989. * @param source the JSON source to parse
  41990. * @return The parsed curves
  41991. */
  41992. ColorCurves.Parse = function (source) {
  41993. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41994. };
  41995. __decorate([
  41996. BABYLON.serialize()
  41997. ], ColorCurves.prototype, "_globalHue", void 0);
  41998. __decorate([
  41999. BABYLON.serialize()
  42000. ], ColorCurves.prototype, "_globalDensity", void 0);
  42001. __decorate([
  42002. BABYLON.serialize()
  42003. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42004. __decorate([
  42005. BABYLON.serialize()
  42006. ], ColorCurves.prototype, "_globalExposure", void 0);
  42007. __decorate([
  42008. BABYLON.serialize()
  42009. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42010. __decorate([
  42011. BABYLON.serialize()
  42012. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42013. __decorate([
  42014. BABYLON.serialize()
  42015. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42016. __decorate([
  42017. BABYLON.serialize()
  42018. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42019. __decorate([
  42020. BABYLON.serialize()
  42021. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42022. __decorate([
  42023. BABYLON.serialize()
  42024. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42025. __decorate([
  42026. BABYLON.serialize()
  42027. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42028. __decorate([
  42029. BABYLON.serialize()
  42030. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42031. return ColorCurves;
  42032. }());
  42033. BABYLON.ColorCurves = ColorCurves;
  42034. })(BABYLON || (BABYLON = {}));
  42035. //# sourceMappingURL=babylon.colorCurves.js.map
  42036. //# sourceMappingURL=babylon.behavior.js.map
  42037. var BABYLON;
  42038. (function (BABYLON) {
  42039. /**
  42040. * "Static Class" containing the most commonly used helper while dealing with material for
  42041. * rendering purpose.
  42042. *
  42043. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42044. *
  42045. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42046. */
  42047. var MaterialHelper = /** @class */ (function () {
  42048. function MaterialHelper() {
  42049. }
  42050. /**
  42051. * Bind the current view position to an effect.
  42052. * @param effect The effect to be bound
  42053. * @param scene The scene the eyes position is used from
  42054. */
  42055. MaterialHelper.BindEyePosition = function (effect, scene) {
  42056. if (scene._forcedViewPosition) {
  42057. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42058. return;
  42059. }
  42060. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42061. };
  42062. /**
  42063. * Helps preparing the defines values about the UVs in used in the effect.
  42064. * UVs are shared as much as we can accross chanels in the shaders.
  42065. * @param texture The texture we are preparing the UVs for
  42066. * @param defines The defines to update
  42067. * @param key The chanel key "diffuse", "specular"... used in the shader
  42068. */
  42069. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42070. defines._needUVs = true;
  42071. defines[key] = true;
  42072. if (texture.getTextureMatrix().isIdentity(true)) {
  42073. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42074. if (texture.coordinatesIndex === 0) {
  42075. defines["MAINUV1"] = true;
  42076. }
  42077. else {
  42078. defines["MAINUV2"] = true;
  42079. }
  42080. }
  42081. else {
  42082. defines[key + "DIRECTUV"] = 0;
  42083. }
  42084. };
  42085. /**
  42086. * Binds a texture matrix value to its corrsponding uniform
  42087. * @param texture The texture to bind the matrix for
  42088. * @param uniformBuffer The uniform buffer receivin the data
  42089. * @param key The chanel key "diffuse", "specular"... used in the shader
  42090. */
  42091. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42092. var matrix = texture.getTextureMatrix();
  42093. if (!matrix.isIdentity(true)) {
  42094. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42095. }
  42096. };
  42097. /**
  42098. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42099. * @param mesh defines the current mesh
  42100. * @param scene defines the current scene
  42101. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42102. * @param pointsCloud defines if point cloud rendering has to be turned on
  42103. * @param fogEnabled defines if fog has to be turned on
  42104. * @param alphaTest defines if alpha testing has to be turned on
  42105. * @param defines defines the current list of defines
  42106. */
  42107. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42108. if (defines._areMiscDirty) {
  42109. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42110. defines["POINTSIZE"] = pointsCloud;
  42111. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42112. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42113. defines["ALPHATEST"] = alphaTest;
  42114. }
  42115. };
  42116. /**
  42117. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42118. * @param scene defines the current scene
  42119. * @param engine defines the current engine
  42120. * @param defines specifies the list of active defines
  42121. * @param useInstances defines if instances have to be turned on
  42122. * @param useClipPlane defines if clip plane have to be turned on
  42123. */
  42124. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42125. if (useClipPlane === void 0) { useClipPlane = null; }
  42126. var changed = false;
  42127. if (useClipPlane == null) {
  42128. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42129. }
  42130. if (defines["CLIPPLANE"] !== useClipPlane) {
  42131. defines["CLIPPLANE"] = useClipPlane;
  42132. changed = true;
  42133. }
  42134. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42135. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42136. changed = true;
  42137. }
  42138. if (defines["INSTANCES"] !== useInstances) {
  42139. defines["INSTANCES"] = useInstances;
  42140. changed = true;
  42141. }
  42142. if (changed) {
  42143. defines.markAsUnprocessed();
  42144. }
  42145. };
  42146. /**
  42147. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42148. * @param mesh The mesh containing the geometry data we will draw
  42149. * @param defines The defines to update
  42150. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42151. * @param useBones Precise whether bones should be used or not (override mesh info)
  42152. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42153. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42154. * @returns false if defines are considered not dirty and have not been checked
  42155. */
  42156. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42157. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42158. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42159. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42160. return false;
  42161. }
  42162. defines._normals = defines._needNormals;
  42163. defines._uvs = defines._needUVs;
  42164. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42165. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42166. defines["TANGENT"] = true;
  42167. }
  42168. if (defines._needUVs) {
  42169. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42170. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42171. }
  42172. else {
  42173. defines["UV1"] = false;
  42174. defines["UV2"] = false;
  42175. }
  42176. if (useVertexColor) {
  42177. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42178. defines["VERTEXCOLOR"] = hasVertexColors;
  42179. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42180. }
  42181. if (useBones) {
  42182. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42183. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42184. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42185. }
  42186. else {
  42187. defines["NUM_BONE_INFLUENCERS"] = 0;
  42188. defines["BonesPerMesh"] = 0;
  42189. }
  42190. }
  42191. if (useMorphTargets) {
  42192. var manager = mesh.morphTargetManager;
  42193. if (manager) {
  42194. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42195. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42196. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42197. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42198. }
  42199. else {
  42200. defines["MORPHTARGETS_TANGENT"] = false;
  42201. defines["MORPHTARGETS_NORMAL"] = false;
  42202. defines["MORPHTARGETS"] = false;
  42203. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42204. }
  42205. }
  42206. return true;
  42207. };
  42208. /**
  42209. * Prepares the defines related to the light information passed in parameter
  42210. * @param scene The scene we are intending to draw
  42211. * @param mesh The mesh the effect is compiling for
  42212. * @param defines The defines to update
  42213. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42214. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42215. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42216. * @returns true if normals will be required for the rest of the effect
  42217. */
  42218. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42219. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42220. if (disableLighting === void 0) { disableLighting = false; }
  42221. if (!defines._areLightsDirty) {
  42222. return defines._needNormals;
  42223. }
  42224. var lightIndex = 0;
  42225. var needNormals = false;
  42226. var needRebuild = false;
  42227. var lightmapMode = false;
  42228. var shadowEnabled = false;
  42229. var specularEnabled = false;
  42230. if (scene.lightsEnabled && !disableLighting) {
  42231. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42232. var light = _a[_i];
  42233. needNormals = true;
  42234. if (defines["LIGHT" + lightIndex] === undefined) {
  42235. needRebuild = true;
  42236. }
  42237. defines["LIGHT" + lightIndex] = true;
  42238. defines["SPOTLIGHT" + lightIndex] = false;
  42239. defines["HEMILIGHT" + lightIndex] = false;
  42240. defines["POINTLIGHT" + lightIndex] = false;
  42241. defines["DIRLIGHT" + lightIndex] = false;
  42242. var type;
  42243. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42244. type = "SPOTLIGHT" + lightIndex;
  42245. var spotLight = light;
  42246. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42247. }
  42248. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42249. type = "HEMILIGHT" + lightIndex;
  42250. }
  42251. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42252. type = "POINTLIGHT" + lightIndex;
  42253. }
  42254. else {
  42255. type = "DIRLIGHT" + lightIndex;
  42256. }
  42257. defines[type] = true;
  42258. // Specular
  42259. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42260. specularEnabled = true;
  42261. }
  42262. // Shadows
  42263. defines["SHADOW" + lightIndex] = false;
  42264. defines["SHADOWPCF" + lightIndex] = false;
  42265. defines["SHADOWPCSS" + lightIndex] = false;
  42266. defines["SHADOWPOISSON" + lightIndex] = false;
  42267. defines["SHADOWESM" + lightIndex] = false;
  42268. defines["SHADOWCUBE" + lightIndex] = false;
  42269. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42270. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42271. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42272. var shadowGenerator = light.getShadowGenerator();
  42273. if (shadowGenerator) {
  42274. shadowEnabled = true;
  42275. shadowGenerator.prepareDefines(defines, lightIndex);
  42276. }
  42277. }
  42278. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42279. lightmapMode = true;
  42280. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42281. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42282. }
  42283. else {
  42284. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42285. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42286. }
  42287. lightIndex++;
  42288. if (lightIndex === maxSimultaneousLights)
  42289. break;
  42290. }
  42291. }
  42292. defines["SPECULARTERM"] = specularEnabled;
  42293. defines["SHADOWS"] = shadowEnabled;
  42294. // Resetting all other lights if any
  42295. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42296. if (defines["LIGHT" + index] !== undefined) {
  42297. defines["LIGHT" + index] = false;
  42298. defines["HEMILIGHT" + lightIndex] = false;
  42299. defines["POINTLIGHT" + lightIndex] = false;
  42300. defines["DIRLIGHT" + lightIndex] = false;
  42301. defines["SPOTLIGHT" + lightIndex] = false;
  42302. defines["SHADOW" + lightIndex] = false;
  42303. }
  42304. }
  42305. var caps = scene.getEngine().getCaps();
  42306. if (defines["SHADOWFLOAT"] === undefined) {
  42307. needRebuild = true;
  42308. }
  42309. defines["SHADOWFLOAT"] = shadowEnabled &&
  42310. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42311. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42312. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42313. if (needRebuild) {
  42314. defines.rebuild();
  42315. }
  42316. return needNormals;
  42317. };
  42318. /**
  42319. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42320. * that won t be acctive due to defines being turned off.
  42321. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42322. * @param samplersList The samplers list
  42323. * @param defines The defines helping in the list generation
  42324. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42325. */
  42326. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42327. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42328. var uniformsList;
  42329. var uniformBuffersList = null;
  42330. if (uniformsListOrOptions.uniformsNames) {
  42331. var options = uniformsListOrOptions;
  42332. uniformsList = options.uniformsNames;
  42333. uniformBuffersList = options.uniformBuffersNames;
  42334. samplersList = options.samplers;
  42335. defines = options.defines;
  42336. maxSimultaneousLights = options.maxSimultaneousLights;
  42337. }
  42338. else {
  42339. uniformsList = uniformsListOrOptions;
  42340. if (!samplersList) {
  42341. samplersList = [];
  42342. }
  42343. }
  42344. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42345. if (!defines["LIGHT" + lightIndex]) {
  42346. break;
  42347. }
  42348. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42349. if (uniformBuffersList) {
  42350. uniformBuffersList.push("Light" + lightIndex);
  42351. }
  42352. samplersList.push("shadowSampler" + lightIndex);
  42353. samplersList.push("depthSampler" + lightIndex);
  42354. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42355. samplersList.push("projectionLightSampler" + lightIndex);
  42356. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42357. }
  42358. }
  42359. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42360. uniformsList.push("morphTargetInfluences");
  42361. }
  42362. };
  42363. /**
  42364. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42365. * @param defines The defines to update while falling back
  42366. * @param fallbacks The authorized effect fallbacks
  42367. * @param maxSimultaneousLights The maximum number of lights allowed
  42368. * @param rank the current rank of the Effect
  42369. * @returns The newly affected rank
  42370. */
  42371. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42372. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42373. if (rank === void 0) { rank = 0; }
  42374. var lightFallbackRank = 0;
  42375. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42376. if (!defines["LIGHT" + lightIndex]) {
  42377. break;
  42378. }
  42379. if (lightIndex > 0) {
  42380. lightFallbackRank = rank + lightIndex;
  42381. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42382. }
  42383. if (!defines["SHADOWS"]) {
  42384. if (defines["SHADOW" + lightIndex]) {
  42385. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42386. }
  42387. if (defines["SHADOWPCF" + lightIndex]) {
  42388. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42389. }
  42390. if (defines["SHADOWPCSS" + lightIndex]) {
  42391. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42392. }
  42393. if (defines["SHADOWPOISSON" + lightIndex]) {
  42394. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42395. }
  42396. if (defines["SHADOWESM" + lightIndex]) {
  42397. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42398. }
  42399. }
  42400. }
  42401. return lightFallbackRank++;
  42402. };
  42403. /**
  42404. * Prepares the list of attributes required for morph targets according to the effect defines.
  42405. * @param attribs The current list of supported attribs
  42406. * @param mesh The mesh to prepare the morph targets attributes for
  42407. * @param defines The current Defines of the effect
  42408. */
  42409. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42410. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42411. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42412. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42413. var manager = mesh.morphTargetManager;
  42414. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42415. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42416. for (var index = 0; index < influencers; index++) {
  42417. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42418. if (normal) {
  42419. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42420. }
  42421. if (tangent) {
  42422. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42423. }
  42424. if (attribs.length > maxAttributesCount) {
  42425. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42426. }
  42427. }
  42428. }
  42429. };
  42430. /**
  42431. * Prepares the list of attributes required for bones according to the effect defines.
  42432. * @param attribs The current list of supported attribs
  42433. * @param mesh The mesh to prepare the bones attributes for
  42434. * @param defines The current Defines of the effect
  42435. * @param fallbacks The current efffect fallback strategy
  42436. */
  42437. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42438. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42439. fallbacks.addCPUSkinningFallback(0, mesh);
  42440. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42441. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42442. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42443. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42444. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42445. }
  42446. }
  42447. };
  42448. /**
  42449. * Prepares the list of attributes required for instances according to the effect defines.
  42450. * @param attribs The current list of supported attribs
  42451. * @param defines The current Defines of the effect
  42452. */
  42453. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42454. if (defines["INSTANCES"]) {
  42455. attribs.push("world0");
  42456. attribs.push("world1");
  42457. attribs.push("world2");
  42458. attribs.push("world3");
  42459. }
  42460. };
  42461. /**
  42462. * Binds the light shadow information to the effect for the given mesh.
  42463. * @param light The light containing the generator
  42464. * @param scene The scene the lights belongs to
  42465. * @param mesh The mesh we are binding the information to render
  42466. * @param lightIndex The light index in the effect used to render the mesh
  42467. * @param effect The effect we are binding the data to
  42468. */
  42469. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42470. if (light.shadowEnabled && mesh.receiveShadows) {
  42471. var shadowGenerator = light.getShadowGenerator();
  42472. if (shadowGenerator) {
  42473. shadowGenerator.bindShadowLight(lightIndex, effect);
  42474. }
  42475. }
  42476. };
  42477. /**
  42478. * Binds the light information to the effect.
  42479. * @param light The light containing the generator
  42480. * @param effect The effect we are binding the data to
  42481. * @param lightIndex The light index in the effect used to render
  42482. */
  42483. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42484. light.transferToEffect(effect, lightIndex + "");
  42485. };
  42486. /**
  42487. * Binds the lights information from the scene to the effect for the given mesh.
  42488. * @param scene The scene the lights belongs to
  42489. * @param mesh The mesh we are binding the information to render
  42490. * @param effect The effect we are binding the data to
  42491. * @param defines The generated defines for the effect
  42492. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42493. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42494. */
  42495. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42496. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42497. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42498. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42499. for (var i = 0; i < len; i++) {
  42500. var light = mesh._lightSources[i];
  42501. var iAsString = i.toString();
  42502. var scaledIntensity = light.getScaledIntensity();
  42503. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42504. MaterialHelper.BindLightProperties(light, effect, i);
  42505. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42506. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42507. if (defines["SPECULARTERM"]) {
  42508. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42509. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42510. }
  42511. // Shadows
  42512. if (scene.shadowsEnabled) {
  42513. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42514. }
  42515. light._uniformBuffer.update();
  42516. }
  42517. };
  42518. /**
  42519. * Binds the fog information from the scene to the effect for the given mesh.
  42520. * @param scene The scene the lights belongs to
  42521. * @param mesh The mesh we are binding the information to render
  42522. * @param effect The effect we are binding the data to
  42523. */
  42524. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42525. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42526. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42527. effect.setColor3("vFogColor", scene.fogColor);
  42528. }
  42529. };
  42530. /**
  42531. * Binds the bones information from the mesh to the effect.
  42532. * @param mesh The mesh we are binding the information to render
  42533. * @param effect The effect we are binding the data to
  42534. */
  42535. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42536. if (!effect || !mesh) {
  42537. return;
  42538. }
  42539. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42540. mesh.computeBonesUsingShaders = false;
  42541. }
  42542. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42543. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42544. if (matrices) {
  42545. effect.setMatrices("mBones", matrices);
  42546. }
  42547. }
  42548. };
  42549. /**
  42550. * Binds the morph targets information from the mesh to the effect.
  42551. * @param abstractMesh The mesh we are binding the information to render
  42552. * @param effect The effect we are binding the data to
  42553. */
  42554. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42555. var manager = abstractMesh.morphTargetManager;
  42556. if (!abstractMesh || !manager) {
  42557. return;
  42558. }
  42559. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42560. };
  42561. /**
  42562. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42563. * @param defines The generated defines used in the effect
  42564. * @param effect The effect we are binding the data to
  42565. * @param scene The scene we are willing to render with logarithmic scale for
  42566. */
  42567. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42568. if (defines["LOGARITHMICDEPTH"]) {
  42569. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42570. }
  42571. };
  42572. /**
  42573. * Binds the clip plane information from the scene to the effect.
  42574. * @param scene The scene the clip plane information are extracted from
  42575. * @param effect The effect we are binding the data to
  42576. */
  42577. MaterialHelper.BindClipPlane = function (effect, scene) {
  42578. if (scene.clipPlane) {
  42579. var clipPlane = scene.clipPlane;
  42580. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42581. }
  42582. };
  42583. return MaterialHelper;
  42584. }());
  42585. BABYLON.MaterialHelper = MaterialHelper;
  42586. })(BABYLON || (BABYLON = {}));
  42587. //# sourceMappingURL=babylon.materialHelper.js.map
  42588. var BABYLON;
  42589. (function (BABYLON) {
  42590. var PushMaterial = /** @class */ (function (_super) {
  42591. __extends(PushMaterial, _super);
  42592. function PushMaterial(name, scene) {
  42593. var _this = _super.call(this, name, scene) || this;
  42594. _this._normalMatrix = new BABYLON.Matrix();
  42595. _this.storeEffectOnSubMeshes = true;
  42596. return _this;
  42597. }
  42598. PushMaterial.prototype.getEffect = function () {
  42599. return this._activeEffect;
  42600. };
  42601. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42602. if (!mesh) {
  42603. return false;
  42604. }
  42605. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42606. return true;
  42607. }
  42608. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42609. };
  42610. /**
  42611. * Binds the given world matrix to the active effect
  42612. *
  42613. * @param world the matrix to bind
  42614. */
  42615. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42616. this._activeEffect.setMatrix("world", world);
  42617. };
  42618. /**
  42619. * Binds the given normal matrix to the active effect
  42620. *
  42621. * @param normalMatrix the matrix to bind
  42622. */
  42623. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42624. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42625. };
  42626. PushMaterial.prototype.bind = function (world, mesh) {
  42627. if (!mesh) {
  42628. return;
  42629. }
  42630. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42631. };
  42632. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42633. if (effect === void 0) { effect = null; }
  42634. _super.prototype._afterBind.call(this, mesh);
  42635. this.getScene()._cachedEffect = effect;
  42636. };
  42637. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42638. if (visibility === void 0) { visibility = 1; }
  42639. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42640. };
  42641. return PushMaterial;
  42642. }(BABYLON.Material));
  42643. BABYLON.PushMaterial = PushMaterial;
  42644. })(BABYLON || (BABYLON = {}));
  42645. //# sourceMappingURL=babylon.pushMaterial.js.map
  42646. var BABYLON;
  42647. (function (BABYLON) {
  42648. /** @hidden */
  42649. var StandardMaterialDefines = /** @class */ (function (_super) {
  42650. __extends(StandardMaterialDefines, _super);
  42651. function StandardMaterialDefines() {
  42652. var _this = _super.call(this) || this;
  42653. _this.MAINUV1 = false;
  42654. _this.MAINUV2 = false;
  42655. _this.DIFFUSE = false;
  42656. _this.DIFFUSEDIRECTUV = 0;
  42657. _this.AMBIENT = false;
  42658. _this.AMBIENTDIRECTUV = 0;
  42659. _this.OPACITY = false;
  42660. _this.OPACITYDIRECTUV = 0;
  42661. _this.OPACITYRGB = false;
  42662. _this.REFLECTION = false;
  42663. _this.EMISSIVE = false;
  42664. _this.EMISSIVEDIRECTUV = 0;
  42665. _this.SPECULAR = false;
  42666. _this.SPECULARDIRECTUV = 0;
  42667. _this.BUMP = false;
  42668. _this.BUMPDIRECTUV = 0;
  42669. _this.PARALLAX = false;
  42670. _this.PARALLAXOCCLUSION = false;
  42671. _this.SPECULAROVERALPHA = false;
  42672. _this.CLIPPLANE = false;
  42673. _this.ALPHATEST = false;
  42674. _this.DEPTHPREPASS = false;
  42675. _this.ALPHAFROMDIFFUSE = false;
  42676. _this.POINTSIZE = false;
  42677. _this.FOG = false;
  42678. _this.SPECULARTERM = false;
  42679. _this.DIFFUSEFRESNEL = false;
  42680. _this.OPACITYFRESNEL = false;
  42681. _this.REFLECTIONFRESNEL = false;
  42682. _this.REFRACTIONFRESNEL = false;
  42683. _this.EMISSIVEFRESNEL = false;
  42684. _this.FRESNEL = false;
  42685. _this.NORMAL = false;
  42686. _this.UV1 = false;
  42687. _this.UV2 = false;
  42688. _this.VERTEXCOLOR = false;
  42689. _this.VERTEXALPHA = false;
  42690. _this.NUM_BONE_INFLUENCERS = 0;
  42691. _this.BonesPerMesh = 0;
  42692. _this.INSTANCES = false;
  42693. _this.GLOSSINESS = false;
  42694. _this.ROUGHNESS = false;
  42695. _this.EMISSIVEASILLUMINATION = false;
  42696. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42697. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42698. _this.LIGHTMAP = false;
  42699. _this.LIGHTMAPDIRECTUV = 0;
  42700. _this.OBJECTSPACE_NORMALMAP = false;
  42701. _this.USELIGHTMAPASSHADOWMAP = false;
  42702. _this.REFLECTIONMAP_3D = false;
  42703. _this.REFLECTIONMAP_SPHERICAL = false;
  42704. _this.REFLECTIONMAP_PLANAR = false;
  42705. _this.REFLECTIONMAP_CUBIC = false;
  42706. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42707. _this.REFLECTIONMAP_PROJECTION = false;
  42708. _this.REFLECTIONMAP_SKYBOX = false;
  42709. _this.REFLECTIONMAP_EXPLICIT = false;
  42710. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42711. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42712. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42713. _this.INVERTCUBICMAP = false;
  42714. _this.LOGARITHMICDEPTH = false;
  42715. _this.REFRACTION = false;
  42716. _this.REFRACTIONMAP_3D = false;
  42717. _this.REFLECTIONOVERALPHA = false;
  42718. _this.TWOSIDEDLIGHTING = false;
  42719. _this.SHADOWFLOAT = false;
  42720. _this.MORPHTARGETS = false;
  42721. _this.MORPHTARGETS_NORMAL = false;
  42722. _this.MORPHTARGETS_TANGENT = false;
  42723. _this.NUM_MORPH_INFLUENCERS = 0;
  42724. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42725. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42726. _this.IMAGEPROCESSING = false;
  42727. _this.VIGNETTE = false;
  42728. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42729. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42730. _this.TONEMAPPING = false;
  42731. _this.CONTRAST = false;
  42732. _this.COLORCURVES = false;
  42733. _this.COLORGRADING = false;
  42734. _this.COLORGRADING3D = false;
  42735. _this.SAMPLER3DGREENDEPTH = false;
  42736. _this.SAMPLER3DBGRMAP = false;
  42737. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42738. /**
  42739. * If the reflection texture on this material is in linear color space
  42740. * @hidden
  42741. */
  42742. _this.IS_REFLECTION_LINEAR = false;
  42743. /**
  42744. * If the refraction texture on this material is in linear color space
  42745. * @hidden
  42746. */
  42747. _this.IS_REFRACTION_LINEAR = false;
  42748. _this.EXPOSURE = false;
  42749. _this.rebuild();
  42750. return _this;
  42751. }
  42752. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42753. var modes = [
  42754. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42755. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42756. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42757. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42758. ];
  42759. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42760. var mode = modes_1[_i];
  42761. this[mode] = (mode === modeToEnable);
  42762. }
  42763. };
  42764. return StandardMaterialDefines;
  42765. }(BABYLON.MaterialDefines));
  42766. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42767. var StandardMaterial = /** @class */ (function (_super) {
  42768. __extends(StandardMaterial, _super);
  42769. function StandardMaterial(name, scene) {
  42770. var _this = _super.call(this, name, scene) || this;
  42771. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42772. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42773. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42774. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42775. _this.specularPower = 64;
  42776. _this._useAlphaFromDiffuseTexture = false;
  42777. _this._useEmissiveAsIllumination = false;
  42778. _this._linkEmissiveWithDiffuse = false;
  42779. _this._useSpecularOverAlpha = false;
  42780. _this._useReflectionOverAlpha = false;
  42781. _this._disableLighting = false;
  42782. _this._useObjectSpaceNormalMap = false;
  42783. _this._useParallax = false;
  42784. _this._useParallaxOcclusion = false;
  42785. _this.parallaxScaleBias = 0.05;
  42786. _this._roughness = 0;
  42787. _this.indexOfRefraction = 0.98;
  42788. _this.invertRefractionY = true;
  42789. /**
  42790. * Defines the alpha limits in alpha test mode
  42791. */
  42792. _this.alphaCutOff = 0.4;
  42793. _this._useLightmapAsShadowmap = false;
  42794. _this._useReflectionFresnelFromSpecular = false;
  42795. _this._useGlossinessFromSpecularMapAlpha = false;
  42796. _this._maxSimultaneousLights = 4;
  42797. /**
  42798. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42799. */
  42800. _this._invertNormalMapX = false;
  42801. /**
  42802. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42803. */
  42804. _this._invertNormalMapY = false;
  42805. /**
  42806. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42807. */
  42808. _this._twoSidedLighting = false;
  42809. _this._renderTargets = new BABYLON.SmartArray(16);
  42810. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42811. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42812. // Setup the default processing configuration to the scene.
  42813. _this._attachImageProcessingConfiguration(null);
  42814. _this.getRenderTargetTextures = function () {
  42815. _this._renderTargets.reset();
  42816. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42817. _this._renderTargets.push(_this._reflectionTexture);
  42818. }
  42819. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42820. _this._renderTargets.push(_this._refractionTexture);
  42821. }
  42822. return _this._renderTargets;
  42823. };
  42824. return _this;
  42825. }
  42826. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42827. /**
  42828. * Gets the image processing configuration used either in this material.
  42829. */
  42830. get: function () {
  42831. return this._imageProcessingConfiguration;
  42832. },
  42833. /**
  42834. * Sets the Default image processing configuration used either in the this material.
  42835. *
  42836. * If sets to null, the scene one is in use.
  42837. */
  42838. set: function (value) {
  42839. this._attachImageProcessingConfiguration(value);
  42840. // Ensure the effect will be rebuilt.
  42841. this._markAllSubMeshesAsTexturesDirty();
  42842. },
  42843. enumerable: true,
  42844. configurable: true
  42845. });
  42846. /**
  42847. * Attaches a new image processing configuration to the Standard Material.
  42848. * @param configuration
  42849. */
  42850. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42851. var _this = this;
  42852. if (configuration === this._imageProcessingConfiguration) {
  42853. return;
  42854. }
  42855. // Detaches observer.
  42856. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42857. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42858. }
  42859. // Pick the scene configuration if needed.
  42860. if (!configuration) {
  42861. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42862. }
  42863. else {
  42864. this._imageProcessingConfiguration = configuration;
  42865. }
  42866. // Attaches observer.
  42867. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42868. _this._markAllSubMeshesAsImageProcessingDirty();
  42869. });
  42870. };
  42871. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42872. /**
  42873. * Gets wether the color curves effect is enabled.
  42874. */
  42875. get: function () {
  42876. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42877. },
  42878. /**
  42879. * Sets wether the color curves effect is enabled.
  42880. */
  42881. set: function (value) {
  42882. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42883. },
  42884. enumerable: true,
  42885. configurable: true
  42886. });
  42887. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42888. /**
  42889. * Gets wether the color grading effect is enabled.
  42890. */
  42891. get: function () {
  42892. return this.imageProcessingConfiguration.colorGradingEnabled;
  42893. },
  42894. /**
  42895. * Gets wether the color grading effect is enabled.
  42896. */
  42897. set: function (value) {
  42898. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42899. },
  42900. enumerable: true,
  42901. configurable: true
  42902. });
  42903. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42904. /**
  42905. * Gets wether tonemapping is enabled or not.
  42906. */
  42907. get: function () {
  42908. return this._imageProcessingConfiguration.toneMappingEnabled;
  42909. },
  42910. /**
  42911. * Sets wether tonemapping is enabled or not
  42912. */
  42913. set: function (value) {
  42914. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42915. },
  42916. enumerable: true,
  42917. configurable: true
  42918. });
  42919. ;
  42920. ;
  42921. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42922. /**
  42923. * The camera exposure used on this material.
  42924. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42925. * This corresponds to a photographic exposure.
  42926. */
  42927. get: function () {
  42928. return this._imageProcessingConfiguration.exposure;
  42929. },
  42930. /**
  42931. * The camera exposure used on this material.
  42932. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42933. * This corresponds to a photographic exposure.
  42934. */
  42935. set: function (value) {
  42936. this._imageProcessingConfiguration.exposure = value;
  42937. },
  42938. enumerable: true,
  42939. configurable: true
  42940. });
  42941. ;
  42942. ;
  42943. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42944. /**
  42945. * Gets The camera contrast used on this material.
  42946. */
  42947. get: function () {
  42948. return this._imageProcessingConfiguration.contrast;
  42949. },
  42950. /**
  42951. * Sets The camera contrast used on this material.
  42952. */
  42953. set: function (value) {
  42954. this._imageProcessingConfiguration.contrast = value;
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42960. /**
  42961. * Gets the Color Grading 2D Lookup Texture.
  42962. */
  42963. get: function () {
  42964. return this._imageProcessingConfiguration.colorGradingTexture;
  42965. },
  42966. /**
  42967. * Sets the Color Grading 2D Lookup Texture.
  42968. */
  42969. set: function (value) {
  42970. this._imageProcessingConfiguration.colorGradingTexture = value;
  42971. },
  42972. enumerable: true,
  42973. configurable: true
  42974. });
  42975. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42976. /**
  42977. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42978. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42979. * 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;
  42980. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42981. */
  42982. get: function () {
  42983. return this._imageProcessingConfiguration.colorCurves;
  42984. },
  42985. /**
  42986. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42987. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42988. * 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;
  42989. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42990. */
  42991. set: function (value) {
  42992. this._imageProcessingConfiguration.colorCurves = value;
  42993. },
  42994. enumerable: true,
  42995. configurable: true
  42996. });
  42997. StandardMaterial.prototype.getClassName = function () {
  42998. return "StandardMaterial";
  42999. };
  43000. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43001. get: function () {
  43002. return this._useLogarithmicDepth;
  43003. },
  43004. set: function (value) {
  43005. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43006. this._markAllSubMeshesAsMiscDirty();
  43007. },
  43008. enumerable: true,
  43009. configurable: true
  43010. });
  43011. StandardMaterial.prototype.needAlphaBlending = function () {
  43012. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43013. };
  43014. StandardMaterial.prototype.needAlphaTesting = function () {
  43015. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43016. };
  43017. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43018. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43019. };
  43020. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43021. return this._diffuseTexture;
  43022. };
  43023. /**
  43024. * Child classes can use it to update shaders
  43025. */
  43026. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43027. if (useInstances === void 0) { useInstances = false; }
  43028. if (subMesh.effect && this.isFrozen) {
  43029. if (this._wasPreviouslyReady && subMesh.effect) {
  43030. return true;
  43031. }
  43032. }
  43033. if (!subMesh._materialDefines) {
  43034. subMesh._materialDefines = new StandardMaterialDefines();
  43035. }
  43036. var scene = this.getScene();
  43037. var defines = subMesh._materialDefines;
  43038. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43039. if (defines._renderId === scene.getRenderId()) {
  43040. return true;
  43041. }
  43042. }
  43043. var engine = scene.getEngine();
  43044. // Lights
  43045. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43046. // Textures
  43047. if (defines._areTexturesDirty) {
  43048. defines._needUVs = false;
  43049. defines.MAINUV1 = false;
  43050. defines.MAINUV2 = false;
  43051. if (scene.texturesEnabled) {
  43052. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43053. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43054. return false;
  43055. }
  43056. else {
  43057. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43058. }
  43059. }
  43060. else {
  43061. defines.DIFFUSE = false;
  43062. }
  43063. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43064. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43065. return false;
  43066. }
  43067. else {
  43068. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43069. }
  43070. }
  43071. else {
  43072. defines.AMBIENT = false;
  43073. }
  43074. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43075. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43076. return false;
  43077. }
  43078. else {
  43079. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43080. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43081. }
  43082. }
  43083. else {
  43084. defines.OPACITY = false;
  43085. }
  43086. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43087. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43088. return false;
  43089. }
  43090. else {
  43091. defines._needNormals = true;
  43092. defines.REFLECTION = true;
  43093. defines.ROUGHNESS = (this._roughness > 0);
  43094. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43095. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43096. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43097. switch (this._reflectionTexture.coordinatesMode) {
  43098. case BABYLON.Texture.EXPLICIT_MODE:
  43099. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43100. break;
  43101. case BABYLON.Texture.PLANAR_MODE:
  43102. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43103. break;
  43104. case BABYLON.Texture.PROJECTION_MODE:
  43105. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43106. break;
  43107. case BABYLON.Texture.SKYBOX_MODE:
  43108. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43109. break;
  43110. case BABYLON.Texture.SPHERICAL_MODE:
  43111. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43112. break;
  43113. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43114. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43115. break;
  43116. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43117. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43118. break;
  43119. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43120. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43121. break;
  43122. case BABYLON.Texture.CUBIC_MODE:
  43123. case BABYLON.Texture.INVCUBIC_MODE:
  43124. default:
  43125. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43126. break;
  43127. }
  43128. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43129. }
  43130. }
  43131. else {
  43132. defines.REFLECTION = false;
  43133. }
  43134. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43135. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43136. return false;
  43137. }
  43138. else {
  43139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43140. }
  43141. }
  43142. else {
  43143. defines.EMISSIVE = false;
  43144. }
  43145. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43146. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43147. return false;
  43148. }
  43149. else {
  43150. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43151. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43152. }
  43153. }
  43154. else {
  43155. defines.LIGHTMAP = false;
  43156. }
  43157. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43158. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43159. return false;
  43160. }
  43161. else {
  43162. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43163. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43164. }
  43165. }
  43166. else {
  43167. defines.SPECULAR = false;
  43168. }
  43169. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43170. // Bump texure can not be not blocking.
  43171. if (!this._bumpTexture.isReady()) {
  43172. return false;
  43173. }
  43174. else {
  43175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43176. defines.PARALLAX = this._useParallax;
  43177. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43178. }
  43179. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43180. }
  43181. else {
  43182. defines.BUMP = false;
  43183. }
  43184. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43185. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43186. return false;
  43187. }
  43188. else {
  43189. defines._needUVs = true;
  43190. defines.REFRACTION = true;
  43191. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43192. }
  43193. }
  43194. else {
  43195. defines.REFRACTION = false;
  43196. }
  43197. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43198. }
  43199. else {
  43200. defines.DIFFUSE = false;
  43201. defines.AMBIENT = false;
  43202. defines.OPACITY = false;
  43203. defines.REFLECTION = false;
  43204. defines.EMISSIVE = false;
  43205. defines.LIGHTMAP = false;
  43206. defines.BUMP = false;
  43207. defines.REFRACTION = false;
  43208. }
  43209. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43210. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43211. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43212. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43213. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43214. }
  43215. if (defines._areImageProcessingDirty) {
  43216. if (!this._imageProcessingConfiguration.isReady()) {
  43217. return false;
  43218. }
  43219. this._imageProcessingConfiguration.prepareDefines(defines);
  43220. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43221. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43222. }
  43223. if (defines._areFresnelDirty) {
  43224. if (StandardMaterial.FresnelEnabled) {
  43225. // Fresnel
  43226. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43227. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43228. this._reflectionFresnelParameters) {
  43229. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43230. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43231. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43232. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43233. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43234. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43235. defines._needNormals = true;
  43236. defines.FRESNEL = true;
  43237. }
  43238. }
  43239. else {
  43240. defines.FRESNEL = false;
  43241. }
  43242. }
  43243. // Misc.
  43244. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43245. // Attribs
  43246. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43247. // Values that need to be evaluated on every frame
  43248. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43249. // Get correct effect
  43250. if (defines.isDirty) {
  43251. defines.markAsProcessed();
  43252. scene.resetCachedMaterial();
  43253. // Fallbacks
  43254. var fallbacks = new BABYLON.EffectFallbacks();
  43255. if (defines.REFLECTION) {
  43256. fallbacks.addFallback(0, "REFLECTION");
  43257. }
  43258. if (defines.SPECULAR) {
  43259. fallbacks.addFallback(0, "SPECULAR");
  43260. }
  43261. if (defines.BUMP) {
  43262. fallbacks.addFallback(0, "BUMP");
  43263. }
  43264. if (defines.PARALLAX) {
  43265. fallbacks.addFallback(1, "PARALLAX");
  43266. }
  43267. if (defines.PARALLAXOCCLUSION) {
  43268. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43269. }
  43270. if (defines.SPECULAROVERALPHA) {
  43271. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43272. }
  43273. if (defines.FOG) {
  43274. fallbacks.addFallback(1, "FOG");
  43275. }
  43276. if (defines.POINTSIZE) {
  43277. fallbacks.addFallback(0, "POINTSIZE");
  43278. }
  43279. if (defines.LOGARITHMICDEPTH) {
  43280. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43281. }
  43282. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43283. if (defines.SPECULARTERM) {
  43284. fallbacks.addFallback(0, "SPECULARTERM");
  43285. }
  43286. if (defines.DIFFUSEFRESNEL) {
  43287. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43288. }
  43289. if (defines.OPACITYFRESNEL) {
  43290. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43291. }
  43292. if (defines.REFLECTIONFRESNEL) {
  43293. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43294. }
  43295. if (defines.EMISSIVEFRESNEL) {
  43296. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43297. }
  43298. if (defines.FRESNEL) {
  43299. fallbacks.addFallback(4, "FRESNEL");
  43300. }
  43301. //Attributes
  43302. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43303. if (defines.NORMAL) {
  43304. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43305. }
  43306. if (defines.UV1) {
  43307. attribs.push(BABYLON.VertexBuffer.UVKind);
  43308. }
  43309. if (defines.UV2) {
  43310. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43311. }
  43312. if (defines.VERTEXCOLOR) {
  43313. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43314. }
  43315. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43316. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43317. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43318. var shaderName = "default";
  43319. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43320. "vFogInfos", "vFogColor", "pointSize",
  43321. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43322. "mBones",
  43323. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43324. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43325. "vReflectionPosition", "vReflectionSize",
  43326. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43327. ];
  43328. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43329. var uniformBuffers = ["Material", "Scene"];
  43330. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43331. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43332. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43333. uniformsNames: uniforms,
  43334. uniformBuffersNames: uniformBuffers,
  43335. samplers: samplers,
  43336. defines: defines,
  43337. maxSimultaneousLights: this._maxSimultaneousLights
  43338. });
  43339. if (this.customShaderNameResolve) {
  43340. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43341. }
  43342. var join = defines.toString();
  43343. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43344. attributes: attribs,
  43345. uniformsNames: uniforms,
  43346. uniformBuffersNames: uniformBuffers,
  43347. samplers: samplers,
  43348. defines: join,
  43349. fallbacks: fallbacks,
  43350. onCompiled: this.onCompiled,
  43351. onError: this.onError,
  43352. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43353. }, engine), defines);
  43354. this.buildUniformLayout();
  43355. }
  43356. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43357. return false;
  43358. }
  43359. defines._renderId = scene.getRenderId();
  43360. this._wasPreviouslyReady = true;
  43361. return true;
  43362. };
  43363. StandardMaterial.prototype.buildUniformLayout = function () {
  43364. // Order is important !
  43365. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43366. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43367. this._uniformBuffer.addUniform("opacityParts", 4);
  43368. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43369. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43370. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43371. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43372. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43373. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43374. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43375. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43376. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43377. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43378. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43379. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43380. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43381. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43382. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43383. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43384. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43385. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43386. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43387. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43388. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43389. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43390. this._uniformBuffer.addUniform("specularMatrix", 16);
  43391. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43392. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43393. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43394. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43395. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43396. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43397. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43398. this._uniformBuffer.addUniform("pointSize", 1);
  43399. this._uniformBuffer.create();
  43400. };
  43401. StandardMaterial.prototype.unbind = function () {
  43402. if (this._activeEffect) {
  43403. var needFlag = false;
  43404. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43405. this._activeEffect.setTexture("reflection2DSampler", null);
  43406. needFlag = true;
  43407. }
  43408. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43409. this._activeEffect.setTexture("refraction2DSampler", null);
  43410. needFlag = true;
  43411. }
  43412. if (needFlag) {
  43413. this._markAllSubMeshesAsTexturesDirty();
  43414. }
  43415. }
  43416. _super.prototype.unbind.call(this);
  43417. };
  43418. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43419. var scene = this.getScene();
  43420. var defines = subMesh._materialDefines;
  43421. if (!defines) {
  43422. return;
  43423. }
  43424. var effect = subMesh.effect;
  43425. if (!effect) {
  43426. return;
  43427. }
  43428. this._activeEffect = effect;
  43429. // Matrices
  43430. this.bindOnlyWorldMatrix(world);
  43431. // Normal Matrix
  43432. if (defines.OBJECTSPACE_NORMALMAP) {
  43433. world.toNormalMatrix(this._normalMatrix);
  43434. this.bindOnlyNormalMatrix(this._normalMatrix);
  43435. }
  43436. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43437. // Bones
  43438. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43439. if (mustRebind) {
  43440. this._uniformBuffer.bindToEffect(effect, "Material");
  43441. this.bindViewProjection(effect);
  43442. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43443. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43444. // Fresnel
  43445. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43446. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43447. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43448. }
  43449. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43450. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43451. }
  43452. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43453. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43454. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43455. }
  43456. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43457. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43458. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43459. }
  43460. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43461. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43462. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43463. }
  43464. }
  43465. // Textures
  43466. if (scene.texturesEnabled) {
  43467. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43468. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43469. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43470. if (this._diffuseTexture.hasAlpha) {
  43471. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43472. }
  43473. }
  43474. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43475. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43476. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43477. }
  43478. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43479. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43480. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43481. }
  43482. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43483. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43484. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43485. if (this._reflectionTexture.boundingBoxSize) {
  43486. var cubeTexture = this._reflectionTexture;
  43487. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43488. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43489. }
  43490. }
  43491. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43492. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43493. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43494. }
  43495. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43496. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43497. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43498. }
  43499. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43500. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43501. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43502. }
  43503. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43504. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43505. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43506. if (scene._mirroredCameraPosition) {
  43507. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43508. }
  43509. else {
  43510. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43511. }
  43512. }
  43513. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43514. var depth = 1.0;
  43515. if (!this._refractionTexture.isCube) {
  43516. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43517. if (this._refractionTexture.depth) {
  43518. depth = this._refractionTexture.depth;
  43519. }
  43520. }
  43521. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43522. }
  43523. }
  43524. // Point size
  43525. if (this.pointsCloud) {
  43526. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43527. }
  43528. if (defines.SPECULARTERM) {
  43529. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43530. }
  43531. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43532. // Diffuse
  43533. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43534. }
  43535. // Textures
  43536. if (scene.texturesEnabled) {
  43537. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43538. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43539. }
  43540. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43541. effect.setTexture("ambientSampler", this._ambientTexture);
  43542. }
  43543. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43544. effect.setTexture("opacitySampler", this._opacityTexture);
  43545. }
  43546. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43547. if (this._reflectionTexture.isCube) {
  43548. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43549. }
  43550. else {
  43551. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43552. }
  43553. }
  43554. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43555. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43556. }
  43557. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43558. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43559. }
  43560. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43561. effect.setTexture("specularSampler", this._specularTexture);
  43562. }
  43563. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43564. effect.setTexture("bumpSampler", this._bumpTexture);
  43565. }
  43566. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43567. var depth = 1.0;
  43568. if (this._refractionTexture.isCube) {
  43569. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43570. }
  43571. else {
  43572. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43573. }
  43574. }
  43575. }
  43576. // Clip plane
  43577. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43578. // Colors
  43579. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43580. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43581. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43582. }
  43583. if (mustRebind || !this.isFrozen) {
  43584. // Lights
  43585. if (scene.lightsEnabled && !this._disableLighting) {
  43586. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43587. }
  43588. // View
  43589. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43590. this.bindView(effect);
  43591. }
  43592. // Fog
  43593. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43594. // Morph targets
  43595. if (defines.NUM_MORPH_INFLUENCERS) {
  43596. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43597. }
  43598. // Log. depth
  43599. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43600. // image processing
  43601. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43602. this._imageProcessingConfiguration.bind(this._activeEffect);
  43603. }
  43604. }
  43605. this._uniformBuffer.update();
  43606. this._afterBind(mesh, this._activeEffect);
  43607. };
  43608. StandardMaterial.prototype.getAnimatables = function () {
  43609. var results = [];
  43610. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43611. results.push(this._diffuseTexture);
  43612. }
  43613. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43614. results.push(this._ambientTexture);
  43615. }
  43616. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43617. results.push(this._opacityTexture);
  43618. }
  43619. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43620. results.push(this._reflectionTexture);
  43621. }
  43622. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43623. results.push(this._emissiveTexture);
  43624. }
  43625. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43626. results.push(this._specularTexture);
  43627. }
  43628. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43629. results.push(this._bumpTexture);
  43630. }
  43631. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43632. results.push(this._lightmapTexture);
  43633. }
  43634. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43635. results.push(this._refractionTexture);
  43636. }
  43637. return results;
  43638. };
  43639. StandardMaterial.prototype.getActiveTextures = function () {
  43640. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43641. if (this._diffuseTexture) {
  43642. activeTextures.push(this._diffuseTexture);
  43643. }
  43644. if (this._ambientTexture) {
  43645. activeTextures.push(this._ambientTexture);
  43646. }
  43647. if (this._opacityTexture) {
  43648. activeTextures.push(this._opacityTexture);
  43649. }
  43650. if (this._reflectionTexture) {
  43651. activeTextures.push(this._reflectionTexture);
  43652. }
  43653. if (this._emissiveTexture) {
  43654. activeTextures.push(this._emissiveTexture);
  43655. }
  43656. if (this._specularTexture) {
  43657. activeTextures.push(this._specularTexture);
  43658. }
  43659. if (this._bumpTexture) {
  43660. activeTextures.push(this._bumpTexture);
  43661. }
  43662. if (this._lightmapTexture) {
  43663. activeTextures.push(this._lightmapTexture);
  43664. }
  43665. if (this._refractionTexture) {
  43666. activeTextures.push(this._refractionTexture);
  43667. }
  43668. return activeTextures;
  43669. };
  43670. StandardMaterial.prototype.hasTexture = function (texture) {
  43671. if (_super.prototype.hasTexture.call(this, texture)) {
  43672. return true;
  43673. }
  43674. if (this._diffuseTexture === texture) {
  43675. return true;
  43676. }
  43677. if (this._ambientTexture === texture) {
  43678. return true;
  43679. }
  43680. if (this._opacityTexture === texture) {
  43681. return true;
  43682. }
  43683. if (this._reflectionTexture === texture) {
  43684. return true;
  43685. }
  43686. if (this._emissiveTexture === texture) {
  43687. return true;
  43688. }
  43689. if (this._specularTexture === texture) {
  43690. return true;
  43691. }
  43692. if (this._bumpTexture === texture) {
  43693. return true;
  43694. }
  43695. if (this._lightmapTexture === texture) {
  43696. return true;
  43697. }
  43698. if (this._refractionTexture === texture) {
  43699. return true;
  43700. }
  43701. return false;
  43702. };
  43703. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43704. if (forceDisposeTextures) {
  43705. if (this._diffuseTexture) {
  43706. this._diffuseTexture.dispose();
  43707. }
  43708. if (this._ambientTexture) {
  43709. this._ambientTexture.dispose();
  43710. }
  43711. if (this._opacityTexture) {
  43712. this._opacityTexture.dispose();
  43713. }
  43714. if (this._reflectionTexture) {
  43715. this._reflectionTexture.dispose();
  43716. }
  43717. if (this._emissiveTexture) {
  43718. this._emissiveTexture.dispose();
  43719. }
  43720. if (this._specularTexture) {
  43721. this._specularTexture.dispose();
  43722. }
  43723. if (this._bumpTexture) {
  43724. this._bumpTexture.dispose();
  43725. }
  43726. if (this._lightmapTexture) {
  43727. this._lightmapTexture.dispose();
  43728. }
  43729. if (this._refractionTexture) {
  43730. this._refractionTexture.dispose();
  43731. }
  43732. }
  43733. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43734. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43735. }
  43736. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43737. };
  43738. StandardMaterial.prototype.clone = function (name) {
  43739. var _this = this;
  43740. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43741. result.name = name;
  43742. result.id = name;
  43743. return result;
  43744. };
  43745. StandardMaterial.prototype.serialize = function () {
  43746. return BABYLON.SerializationHelper.Serialize(this);
  43747. };
  43748. // Statics
  43749. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43750. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43751. };
  43752. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43753. get: function () {
  43754. return StandardMaterial._DiffuseTextureEnabled;
  43755. },
  43756. set: function (value) {
  43757. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43758. return;
  43759. }
  43760. StandardMaterial._DiffuseTextureEnabled = value;
  43761. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43762. },
  43763. enumerable: true,
  43764. configurable: true
  43765. });
  43766. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43767. get: function () {
  43768. return StandardMaterial._AmbientTextureEnabled;
  43769. },
  43770. set: function (value) {
  43771. if (StandardMaterial._AmbientTextureEnabled === value) {
  43772. return;
  43773. }
  43774. StandardMaterial._AmbientTextureEnabled = value;
  43775. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43776. },
  43777. enumerable: true,
  43778. configurable: true
  43779. });
  43780. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43781. get: function () {
  43782. return StandardMaterial._OpacityTextureEnabled;
  43783. },
  43784. set: function (value) {
  43785. if (StandardMaterial._OpacityTextureEnabled === value) {
  43786. return;
  43787. }
  43788. StandardMaterial._OpacityTextureEnabled = value;
  43789. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43790. },
  43791. enumerable: true,
  43792. configurable: true
  43793. });
  43794. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43795. get: function () {
  43796. return StandardMaterial._ReflectionTextureEnabled;
  43797. },
  43798. set: function (value) {
  43799. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43800. return;
  43801. }
  43802. StandardMaterial._ReflectionTextureEnabled = value;
  43803. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43804. },
  43805. enumerable: true,
  43806. configurable: true
  43807. });
  43808. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43809. get: function () {
  43810. return StandardMaterial._EmissiveTextureEnabled;
  43811. },
  43812. set: function (value) {
  43813. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43814. return;
  43815. }
  43816. StandardMaterial._EmissiveTextureEnabled = value;
  43817. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43818. },
  43819. enumerable: true,
  43820. configurable: true
  43821. });
  43822. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43823. get: function () {
  43824. return StandardMaterial._SpecularTextureEnabled;
  43825. },
  43826. set: function (value) {
  43827. if (StandardMaterial._SpecularTextureEnabled === value) {
  43828. return;
  43829. }
  43830. StandardMaterial._SpecularTextureEnabled = value;
  43831. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43832. },
  43833. enumerable: true,
  43834. configurable: true
  43835. });
  43836. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43837. get: function () {
  43838. return StandardMaterial._BumpTextureEnabled;
  43839. },
  43840. set: function (value) {
  43841. if (StandardMaterial._BumpTextureEnabled === value) {
  43842. return;
  43843. }
  43844. StandardMaterial._BumpTextureEnabled = value;
  43845. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43846. },
  43847. enumerable: true,
  43848. configurable: true
  43849. });
  43850. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43851. get: function () {
  43852. return StandardMaterial._LightmapTextureEnabled;
  43853. },
  43854. set: function (value) {
  43855. if (StandardMaterial._LightmapTextureEnabled === value) {
  43856. return;
  43857. }
  43858. StandardMaterial._LightmapTextureEnabled = value;
  43859. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43860. },
  43861. enumerable: true,
  43862. configurable: true
  43863. });
  43864. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43865. get: function () {
  43866. return StandardMaterial._RefractionTextureEnabled;
  43867. },
  43868. set: function (value) {
  43869. if (StandardMaterial._RefractionTextureEnabled === value) {
  43870. return;
  43871. }
  43872. StandardMaterial._RefractionTextureEnabled = value;
  43873. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43874. },
  43875. enumerable: true,
  43876. configurable: true
  43877. });
  43878. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43879. get: function () {
  43880. return StandardMaterial._ColorGradingTextureEnabled;
  43881. },
  43882. set: function (value) {
  43883. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43884. return;
  43885. }
  43886. StandardMaterial._ColorGradingTextureEnabled = value;
  43887. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43888. },
  43889. enumerable: true,
  43890. configurable: true
  43891. });
  43892. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43893. get: function () {
  43894. return StandardMaterial._FresnelEnabled;
  43895. },
  43896. set: function (value) {
  43897. if (StandardMaterial._FresnelEnabled === value) {
  43898. return;
  43899. }
  43900. StandardMaterial._FresnelEnabled = value;
  43901. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43902. },
  43903. enumerable: true,
  43904. configurable: true
  43905. });
  43906. // Flags used to enable or disable a type of texture for all Standard Materials
  43907. StandardMaterial._DiffuseTextureEnabled = true;
  43908. StandardMaterial._AmbientTextureEnabled = true;
  43909. StandardMaterial._OpacityTextureEnabled = true;
  43910. StandardMaterial._ReflectionTextureEnabled = true;
  43911. StandardMaterial._EmissiveTextureEnabled = true;
  43912. StandardMaterial._SpecularTextureEnabled = true;
  43913. StandardMaterial._BumpTextureEnabled = true;
  43914. StandardMaterial._LightmapTextureEnabled = true;
  43915. StandardMaterial._RefractionTextureEnabled = true;
  43916. StandardMaterial._ColorGradingTextureEnabled = true;
  43917. StandardMaterial._FresnelEnabled = true;
  43918. __decorate([
  43919. BABYLON.serializeAsTexture("diffuseTexture")
  43920. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43921. __decorate([
  43922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43923. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43924. __decorate([
  43925. BABYLON.serializeAsTexture("ambientTexture")
  43926. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43927. __decorate([
  43928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43929. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43930. __decorate([
  43931. BABYLON.serializeAsTexture("opacityTexture")
  43932. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43933. __decorate([
  43934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43935. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43936. __decorate([
  43937. BABYLON.serializeAsTexture("reflectionTexture")
  43938. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43939. __decorate([
  43940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43941. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43942. __decorate([
  43943. BABYLON.serializeAsTexture("emissiveTexture")
  43944. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43945. __decorate([
  43946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43947. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43948. __decorate([
  43949. BABYLON.serializeAsTexture("specularTexture")
  43950. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43951. __decorate([
  43952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43953. ], StandardMaterial.prototype, "specularTexture", void 0);
  43954. __decorate([
  43955. BABYLON.serializeAsTexture("bumpTexture")
  43956. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43957. __decorate([
  43958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43959. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43960. __decorate([
  43961. BABYLON.serializeAsTexture("lightmapTexture")
  43962. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43963. __decorate([
  43964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43965. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43966. __decorate([
  43967. BABYLON.serializeAsTexture("refractionTexture")
  43968. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43969. __decorate([
  43970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43971. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43972. __decorate([
  43973. BABYLON.serializeAsColor3("ambient")
  43974. ], StandardMaterial.prototype, "ambientColor", void 0);
  43975. __decorate([
  43976. BABYLON.serializeAsColor3("diffuse")
  43977. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43978. __decorate([
  43979. BABYLON.serializeAsColor3("specular")
  43980. ], StandardMaterial.prototype, "specularColor", void 0);
  43981. __decorate([
  43982. BABYLON.serializeAsColor3("emissive")
  43983. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43984. __decorate([
  43985. BABYLON.serialize()
  43986. ], StandardMaterial.prototype, "specularPower", void 0);
  43987. __decorate([
  43988. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43989. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43990. __decorate([
  43991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43992. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43993. __decorate([
  43994. BABYLON.serialize("useEmissiveAsIllumination")
  43995. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43996. __decorate([
  43997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43998. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43999. __decorate([
  44000. BABYLON.serialize("linkEmissiveWithDiffuse")
  44001. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44002. __decorate([
  44003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44004. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44005. __decorate([
  44006. BABYLON.serialize("useSpecularOverAlpha")
  44007. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44008. __decorate([
  44009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44010. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44011. __decorate([
  44012. BABYLON.serialize("useReflectionOverAlpha")
  44013. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44014. __decorate([
  44015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44016. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44017. __decorate([
  44018. BABYLON.serialize("disableLighting")
  44019. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44020. __decorate([
  44021. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44022. ], StandardMaterial.prototype, "disableLighting", void 0);
  44023. __decorate([
  44024. BABYLON.serialize("useObjectSpaceNormalMap")
  44025. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44026. __decorate([
  44027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44028. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44029. __decorate([
  44030. BABYLON.serialize("useParallax")
  44031. ], StandardMaterial.prototype, "_useParallax", void 0);
  44032. __decorate([
  44033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44034. ], StandardMaterial.prototype, "useParallax", void 0);
  44035. __decorate([
  44036. BABYLON.serialize("useParallaxOcclusion")
  44037. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44038. __decorate([
  44039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44040. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44041. __decorate([
  44042. BABYLON.serialize()
  44043. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44044. __decorate([
  44045. BABYLON.serialize("roughness")
  44046. ], StandardMaterial.prototype, "_roughness", void 0);
  44047. __decorate([
  44048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44049. ], StandardMaterial.prototype, "roughness", void 0);
  44050. __decorate([
  44051. BABYLON.serialize()
  44052. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44053. __decorate([
  44054. BABYLON.serialize()
  44055. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44056. __decorate([
  44057. BABYLON.serialize()
  44058. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44059. __decorate([
  44060. BABYLON.serialize("useLightmapAsShadowmap")
  44061. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44062. __decorate([
  44063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44064. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44065. __decorate([
  44066. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44067. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44068. __decorate([
  44069. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44070. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44071. __decorate([
  44072. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44073. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44074. __decorate([
  44075. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44076. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44077. __decorate([
  44078. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44079. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44080. __decorate([
  44081. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44082. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44083. __decorate([
  44084. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44085. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44086. __decorate([
  44087. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44088. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44089. __decorate([
  44090. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44091. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44092. __decorate([
  44093. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44094. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44095. __decorate([
  44096. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44097. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44098. __decorate([
  44099. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44100. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44101. __decorate([
  44102. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44103. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44104. __decorate([
  44105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44106. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44107. __decorate([
  44108. BABYLON.serialize("maxSimultaneousLights")
  44109. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44110. __decorate([
  44111. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44112. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44113. __decorate([
  44114. BABYLON.serialize("invertNormalMapX")
  44115. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44116. __decorate([
  44117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44118. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44119. __decorate([
  44120. BABYLON.serialize("invertNormalMapY")
  44121. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44122. __decorate([
  44123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44124. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44125. __decorate([
  44126. BABYLON.serialize("twoSidedLighting")
  44127. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44128. __decorate([
  44129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44130. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44131. __decorate([
  44132. BABYLON.serialize()
  44133. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44134. return StandardMaterial;
  44135. }(BABYLON.PushMaterial));
  44136. BABYLON.StandardMaterial = StandardMaterial;
  44137. })(BABYLON || (BABYLON = {}));
  44138. //# sourceMappingURL=babylon.standardMaterial.js.map
  44139. var BABYLON;
  44140. (function (BABYLON) {
  44141. /**
  44142. * Manages the defines for the PBR Material.
  44143. * @hiddenChildren
  44144. */
  44145. var PBRMaterialDefines = /** @class */ (function (_super) {
  44146. __extends(PBRMaterialDefines, _super);
  44147. /**
  44148. * Initializes the PBR Material defines.
  44149. */
  44150. function PBRMaterialDefines() {
  44151. var _this = _super.call(this) || this;
  44152. _this.PBR = true;
  44153. _this.MAINUV1 = false;
  44154. _this.MAINUV2 = false;
  44155. _this.UV1 = false;
  44156. _this.UV2 = false;
  44157. _this.ALBEDO = false;
  44158. _this.ALBEDODIRECTUV = 0;
  44159. _this.VERTEXCOLOR = false;
  44160. _this.AMBIENT = false;
  44161. _this.AMBIENTDIRECTUV = 0;
  44162. _this.AMBIENTINGRAYSCALE = false;
  44163. _this.OPACITY = false;
  44164. _this.VERTEXALPHA = false;
  44165. _this.OPACITYDIRECTUV = 0;
  44166. _this.OPACITYRGB = false;
  44167. _this.ALPHATEST = false;
  44168. _this.DEPTHPREPASS = false;
  44169. _this.ALPHABLEND = false;
  44170. _this.ALPHAFROMALBEDO = false;
  44171. _this.ALPHATESTVALUE = "0.5";
  44172. _this.SPECULAROVERALPHA = false;
  44173. _this.RADIANCEOVERALPHA = false;
  44174. _this.ALPHAFRESNEL = false;
  44175. _this.LINEARALPHAFRESNEL = false;
  44176. _this.PREMULTIPLYALPHA = false;
  44177. _this.EMISSIVE = false;
  44178. _this.EMISSIVEDIRECTUV = 0;
  44179. _this.REFLECTIVITY = false;
  44180. _this.REFLECTIVITYDIRECTUV = 0;
  44181. _this.SPECULARTERM = false;
  44182. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44183. _this.MICROSURFACEAUTOMATIC = false;
  44184. _this.LODBASEDMICROSFURACE = false;
  44185. _this.MICROSURFACEMAP = false;
  44186. _this.MICROSURFACEMAPDIRECTUV = 0;
  44187. _this.METALLICWORKFLOW = false;
  44188. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44189. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44190. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44191. _this.AOSTOREINMETALMAPRED = false;
  44192. _this.ENVIRONMENTBRDF = false;
  44193. _this.NORMAL = false;
  44194. _this.TANGENT = false;
  44195. _this.BUMP = false;
  44196. _this.BUMPDIRECTUV = 0;
  44197. _this.OBJECTSPACE_NORMALMAP = false;
  44198. _this.PARALLAX = false;
  44199. _this.PARALLAXOCCLUSION = false;
  44200. _this.NORMALXYSCALE = true;
  44201. _this.LIGHTMAP = false;
  44202. _this.LIGHTMAPDIRECTUV = 0;
  44203. _this.USELIGHTMAPASSHADOWMAP = false;
  44204. _this.GAMMALIGHTMAP = false;
  44205. _this.REFLECTION = false;
  44206. _this.REFLECTIONMAP_3D = false;
  44207. _this.REFLECTIONMAP_SPHERICAL = false;
  44208. _this.REFLECTIONMAP_PLANAR = false;
  44209. _this.REFLECTIONMAP_CUBIC = false;
  44210. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44211. _this.REFLECTIONMAP_PROJECTION = false;
  44212. _this.REFLECTIONMAP_SKYBOX = false;
  44213. _this.REFLECTIONMAP_EXPLICIT = false;
  44214. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44215. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44216. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44217. _this.INVERTCUBICMAP = false;
  44218. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44219. _this.USESPHERICALINVERTEX = false;
  44220. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44221. _this.LODINREFLECTIONALPHA = false;
  44222. _this.GAMMAREFLECTION = false;
  44223. _this.RADIANCEOCCLUSION = false;
  44224. _this.HORIZONOCCLUSION = false;
  44225. _this.REFRACTION = false;
  44226. _this.REFRACTIONMAP_3D = false;
  44227. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44228. _this.LODINREFRACTIONALPHA = false;
  44229. _this.GAMMAREFRACTION = false;
  44230. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44231. _this.INSTANCES = false;
  44232. _this.NUM_BONE_INFLUENCERS = 0;
  44233. _this.BonesPerMesh = 0;
  44234. _this.NONUNIFORMSCALING = false;
  44235. _this.MORPHTARGETS = false;
  44236. _this.MORPHTARGETS_NORMAL = false;
  44237. _this.MORPHTARGETS_TANGENT = false;
  44238. _this.NUM_MORPH_INFLUENCERS = 0;
  44239. _this.IMAGEPROCESSING = false;
  44240. _this.VIGNETTE = false;
  44241. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44242. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44243. _this.TONEMAPPING = false;
  44244. _this.CONTRAST = false;
  44245. _this.COLORCURVES = false;
  44246. _this.COLORGRADING = false;
  44247. _this.COLORGRADING3D = false;
  44248. _this.SAMPLER3DGREENDEPTH = false;
  44249. _this.SAMPLER3DBGRMAP = false;
  44250. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44251. _this.EXPOSURE = false;
  44252. _this.USEPHYSICALLIGHTFALLOFF = false;
  44253. _this.TWOSIDEDLIGHTING = false;
  44254. _this.SHADOWFLOAT = false;
  44255. _this.CLIPPLANE = false;
  44256. _this.POINTSIZE = false;
  44257. _this.FOG = false;
  44258. _this.LOGARITHMICDEPTH = false;
  44259. _this.FORCENORMALFORWARD = false;
  44260. _this.SPECULARAA = false;
  44261. _this.UNLIT = false;
  44262. _this.rebuild();
  44263. return _this;
  44264. }
  44265. /**
  44266. * Resets the PBR Material defines.
  44267. */
  44268. PBRMaterialDefines.prototype.reset = function () {
  44269. _super.prototype.reset.call(this);
  44270. this.ALPHATESTVALUE = "0.5";
  44271. this.PBR = true;
  44272. };
  44273. return PBRMaterialDefines;
  44274. }(BABYLON.MaterialDefines));
  44275. /**
  44276. * The Physically based material base class of BJS.
  44277. *
  44278. * This offers the main features of a standard PBR material.
  44279. * For more information, please refer to the documentation :
  44280. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44281. */
  44282. var PBRBaseMaterial = /** @class */ (function (_super) {
  44283. __extends(PBRBaseMaterial, _super);
  44284. /**
  44285. * Instantiates a new PBRMaterial instance.
  44286. *
  44287. * @param name The material name
  44288. * @param scene The scene the material will be use in.
  44289. */
  44290. function PBRBaseMaterial(name, scene) {
  44291. var _this = _super.call(this, name, scene) || this;
  44292. /**
  44293. * Intensity of the direct lights e.g. the four lights available in your scene.
  44294. * This impacts both the direct diffuse and specular highlights.
  44295. */
  44296. _this._directIntensity = 1.0;
  44297. /**
  44298. * Intensity of the emissive part of the material.
  44299. * This helps controlling the emissive effect without modifying the emissive color.
  44300. */
  44301. _this._emissiveIntensity = 1.0;
  44302. /**
  44303. * Intensity of the environment e.g. how much the environment will light the object
  44304. * either through harmonics for rough material or through the refelction for shiny ones.
  44305. */
  44306. _this._environmentIntensity = 1.0;
  44307. /**
  44308. * This is a special control allowing the reduction of the specular highlights coming from the
  44309. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44310. */
  44311. _this._specularIntensity = 1.0;
  44312. /**
  44313. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44314. */
  44315. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44316. /**
  44317. * Debug Control allowing disabling the bump map on this material.
  44318. */
  44319. _this._disableBumpMap = false;
  44320. /**
  44321. * AKA Occlusion Texture Intensity in other nomenclature.
  44322. */
  44323. _this._ambientTextureStrength = 1.0;
  44324. /**
  44325. * The color of a material in ambient lighting.
  44326. */
  44327. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44328. /**
  44329. * AKA Diffuse Color in other nomenclature.
  44330. */
  44331. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44332. /**
  44333. * AKA Specular Color in other nomenclature.
  44334. */
  44335. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44336. /**
  44337. * The color applied when light is reflected from a material.
  44338. */
  44339. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44340. /**
  44341. * The color applied when light is emitted from a material.
  44342. */
  44343. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44344. /**
  44345. * AKA Glossiness in other nomenclature.
  44346. */
  44347. _this._microSurface = 0.9;
  44348. /**
  44349. * source material index of refraction (IOR)' / 'destination material IOR.
  44350. */
  44351. _this._indexOfRefraction = 0.66;
  44352. /**
  44353. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44354. */
  44355. _this._invertRefractionY = false;
  44356. /**
  44357. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44358. * Materials half opaque for instance using refraction could benefit from this control.
  44359. */
  44360. _this._linkRefractionWithTransparency = false;
  44361. /**
  44362. * Specifies that the material will use the light map as a show map.
  44363. */
  44364. _this._useLightmapAsShadowmap = false;
  44365. /**
  44366. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44367. * makes the reflect vector face the model (under horizon).
  44368. */
  44369. _this._useHorizonOcclusion = true;
  44370. /**
  44371. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44372. * too much the area relying on ambient texture to define their ambient occlusion.
  44373. */
  44374. _this._useRadianceOcclusion = true;
  44375. /**
  44376. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44377. */
  44378. _this._useAlphaFromAlbedoTexture = false;
  44379. /**
  44380. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44381. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44382. */
  44383. _this._useSpecularOverAlpha = true;
  44384. /**
  44385. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44386. */
  44387. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44388. /**
  44389. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44390. */
  44391. _this._useRoughnessFromMetallicTextureAlpha = true;
  44392. /**
  44393. * Specifies if the metallic texture contains the roughness information in its green channel.
  44394. */
  44395. _this._useRoughnessFromMetallicTextureGreen = false;
  44396. /**
  44397. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44398. */
  44399. _this._useMetallnessFromMetallicTextureBlue = false;
  44400. /**
  44401. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44402. */
  44403. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44404. /**
  44405. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44406. */
  44407. _this._useAmbientInGrayScale = false;
  44408. /**
  44409. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44410. * The material will try to infer what glossiness each pixel should be.
  44411. */
  44412. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44413. /**
  44414. * BJS is using an harcoded light falloff based on a manually sets up range.
  44415. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44416. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44417. */
  44418. _this._usePhysicalLightFalloff = true;
  44419. /**
  44420. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44421. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44422. */
  44423. _this._useRadianceOverAlpha = true;
  44424. /**
  44425. * Allows using an object space normal map (instead of tangent space).
  44426. */
  44427. _this._useObjectSpaceNormalMap = false;
  44428. /**
  44429. * Allows using the bump map in parallax mode.
  44430. */
  44431. _this._useParallax = false;
  44432. /**
  44433. * Allows using the bump map in parallax occlusion mode.
  44434. */
  44435. _this._useParallaxOcclusion = false;
  44436. /**
  44437. * Controls the scale bias of the parallax mode.
  44438. */
  44439. _this._parallaxScaleBias = 0.05;
  44440. /**
  44441. * If sets to true, disables all the lights affecting the material.
  44442. */
  44443. _this._disableLighting = false;
  44444. /**
  44445. * Number of Simultaneous lights allowed on the material.
  44446. */
  44447. _this._maxSimultaneousLights = 4;
  44448. /**
  44449. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44450. */
  44451. _this._invertNormalMapX = false;
  44452. /**
  44453. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44454. */
  44455. _this._invertNormalMapY = false;
  44456. /**
  44457. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44458. */
  44459. _this._twoSidedLighting = false;
  44460. /**
  44461. * Defines the alpha limits in alpha test mode.
  44462. */
  44463. _this._alphaCutOff = 0.4;
  44464. /**
  44465. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44466. */
  44467. _this._forceAlphaTest = false;
  44468. /**
  44469. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44470. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44471. */
  44472. _this._useAlphaFresnel = false;
  44473. /**
  44474. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44475. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44476. */
  44477. _this._useLinearAlphaFresnel = false;
  44478. /**
  44479. * The transparency mode of the material.
  44480. */
  44481. _this._transparencyMode = null;
  44482. /**
  44483. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44484. * from cos thetav and roughness:
  44485. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44486. */
  44487. _this._environmentBRDFTexture = null;
  44488. /**
  44489. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44490. */
  44491. _this._forceIrradianceInFragment = false;
  44492. /**
  44493. * Force normal to face away from face.
  44494. */
  44495. _this._forceNormalForward = false;
  44496. /**
  44497. * Enables specular anti aliasing in the PBR shader.
  44498. * It will both interacts on the Geometry for analytical and IBL lighting.
  44499. * It also prefilter the roughness map based on the bump values.
  44500. */
  44501. _this._enableSpecularAntiAliasing = false;
  44502. /**
  44503. * Stores the available render targets.
  44504. */
  44505. _this._renderTargets = new BABYLON.SmartArray(16);
  44506. /**
  44507. * Sets the global ambient color for the material used in lighting calculations.
  44508. */
  44509. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44510. /**
  44511. * If set to true, no lighting calculations will be applied.
  44512. */
  44513. _this._unlit = false;
  44514. // Setup the default processing configuration to the scene.
  44515. _this._attachImageProcessingConfiguration(null);
  44516. _this.getRenderTargetTextures = function () {
  44517. _this._renderTargets.reset();
  44518. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44519. _this._renderTargets.push(_this._reflectionTexture);
  44520. }
  44521. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44522. _this._renderTargets.push(_this._refractionTexture);
  44523. }
  44524. return _this._renderTargets;
  44525. };
  44526. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44527. return _this;
  44528. }
  44529. /**
  44530. * Attaches a new image processing configuration to the PBR Material.
  44531. * @param configuration
  44532. */
  44533. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44534. var _this = this;
  44535. if (configuration === this._imageProcessingConfiguration) {
  44536. return;
  44537. }
  44538. // Detaches observer.
  44539. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44540. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44541. }
  44542. // Pick the scene configuration if needed.
  44543. if (!configuration) {
  44544. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44545. }
  44546. else {
  44547. this._imageProcessingConfiguration = configuration;
  44548. }
  44549. // Attaches observer.
  44550. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44551. _this._markAllSubMeshesAsImageProcessingDirty();
  44552. });
  44553. };
  44554. /**
  44555. * Gets the name of the material class.
  44556. */
  44557. PBRBaseMaterial.prototype.getClassName = function () {
  44558. return "PBRBaseMaterial";
  44559. };
  44560. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44561. /**
  44562. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44563. */
  44564. get: function () {
  44565. return this._useLogarithmicDepth;
  44566. },
  44567. /**
  44568. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44569. */
  44570. set: function (value) {
  44571. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44572. },
  44573. enumerable: true,
  44574. configurable: true
  44575. });
  44576. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44577. /**
  44578. * Gets the current transparency mode.
  44579. */
  44580. get: function () {
  44581. return this._transparencyMode;
  44582. },
  44583. /**
  44584. * Sets the transparency mode of the material.
  44585. */
  44586. set: function (value) {
  44587. if (this._transparencyMode === value) {
  44588. return;
  44589. }
  44590. this._transparencyMode = value;
  44591. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44592. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44598. /**
  44599. * Returns true if alpha blending should be disabled.
  44600. */
  44601. get: function () {
  44602. return (this._linkRefractionWithTransparency ||
  44603. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44604. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44605. },
  44606. enumerable: true,
  44607. configurable: true
  44608. });
  44609. /**
  44610. * Specifies whether or not this material should be rendered in alpha blend mode.
  44611. */
  44612. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44613. if (this._disableAlphaBlending) {
  44614. return false;
  44615. }
  44616. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44617. };
  44618. /**
  44619. * Specifies if the mesh will require alpha blending.
  44620. * @param mesh - BJS mesh.
  44621. */
  44622. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44623. if (this._disableAlphaBlending) {
  44624. return false;
  44625. }
  44626. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44627. };
  44628. /**
  44629. * Specifies whether or not this material should be rendered in alpha test mode.
  44630. */
  44631. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44632. if (this._forceAlphaTest) {
  44633. return true;
  44634. }
  44635. if (this._linkRefractionWithTransparency) {
  44636. return false;
  44637. }
  44638. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44639. };
  44640. /**
  44641. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44642. */
  44643. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44644. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44645. };
  44646. /**
  44647. * Gets the texture used for the alpha test.
  44648. */
  44649. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44650. return this._albedoTexture;
  44651. };
  44652. /**
  44653. * Specifies that the submesh is ready to be used.
  44654. * @param mesh - BJS mesh.
  44655. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44656. * @param useInstances - Specifies that instances should be used.
  44657. * @returns - boolean indicating that the submesh is ready or not.
  44658. */
  44659. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44660. if (subMesh.effect && this.isFrozen) {
  44661. if (this._wasPreviouslyReady) {
  44662. return true;
  44663. }
  44664. }
  44665. if (!subMesh._materialDefines) {
  44666. subMesh._materialDefines = new PBRMaterialDefines();
  44667. }
  44668. var defines = subMesh._materialDefines;
  44669. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44670. if (defines._renderId === this.getScene().getRenderId()) {
  44671. return true;
  44672. }
  44673. }
  44674. var scene = this.getScene();
  44675. var engine = scene.getEngine();
  44676. if (defines._areTexturesDirty) {
  44677. if (scene.texturesEnabled) {
  44678. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44679. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44680. return false;
  44681. }
  44682. }
  44683. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44684. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44685. return false;
  44686. }
  44687. }
  44688. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44689. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44690. return false;
  44691. }
  44692. }
  44693. var reflectionTexture = this._getReflectionTexture();
  44694. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44695. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44696. return false;
  44697. }
  44698. }
  44699. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44700. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44701. return false;
  44702. }
  44703. }
  44704. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44705. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44706. return false;
  44707. }
  44708. }
  44709. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44710. if (this._metallicTexture) {
  44711. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44712. return false;
  44713. }
  44714. }
  44715. else if (this._reflectivityTexture) {
  44716. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44717. return false;
  44718. }
  44719. }
  44720. if (this._microSurfaceTexture) {
  44721. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44722. return false;
  44723. }
  44724. }
  44725. }
  44726. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44727. // Bump texture cannot be not blocking.
  44728. if (!this._bumpTexture.isReady()) {
  44729. return false;
  44730. }
  44731. }
  44732. var refractionTexture = this._getRefractionTexture();
  44733. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44734. if (!refractionTexture.isReadyOrNotBlocking()) {
  44735. return false;
  44736. }
  44737. }
  44738. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44739. // This is blocking.
  44740. if (!this._environmentBRDFTexture.isReady()) {
  44741. return false;
  44742. }
  44743. }
  44744. }
  44745. }
  44746. if (defines._areImageProcessingDirty) {
  44747. if (!this._imageProcessingConfiguration.isReady()) {
  44748. return false;
  44749. }
  44750. }
  44751. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44752. mesh.createNormals(true);
  44753. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44754. }
  44755. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44756. if (effect) {
  44757. scene.resetCachedMaterial();
  44758. subMesh.setEffect(effect, defines);
  44759. this.buildUniformLayout();
  44760. }
  44761. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44762. return false;
  44763. }
  44764. defines._renderId = scene.getRenderId();
  44765. this._wasPreviouslyReady = true;
  44766. return true;
  44767. };
  44768. /**
  44769. * Specifies if the material uses metallic roughness workflow.
  44770. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44771. */
  44772. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44773. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44774. return true;
  44775. }
  44776. return false;
  44777. };
  44778. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44779. if (onCompiled === void 0) { onCompiled = null; }
  44780. if (onError === void 0) { onError = null; }
  44781. if (useInstances === void 0) { useInstances = null; }
  44782. if (useClipPlane === void 0) { useClipPlane = null; }
  44783. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44784. if (!defines.isDirty) {
  44785. return null;
  44786. }
  44787. defines.markAsProcessed();
  44788. var scene = this.getScene();
  44789. var engine = scene.getEngine();
  44790. // Fallbacks
  44791. var fallbacks = new BABYLON.EffectFallbacks();
  44792. var fallbackRank = 0;
  44793. if (defines.USESPHERICALINVERTEX) {
  44794. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44795. }
  44796. if (defines.FOG) {
  44797. fallbacks.addFallback(fallbackRank, "FOG");
  44798. }
  44799. if (defines.SPECULARAA) {
  44800. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44801. }
  44802. if (defines.POINTSIZE) {
  44803. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44804. }
  44805. if (defines.LOGARITHMICDEPTH) {
  44806. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44807. }
  44808. if (defines.PARALLAX) {
  44809. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44810. }
  44811. if (defines.PARALLAXOCCLUSION) {
  44812. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44813. }
  44814. if (defines.ENVIRONMENTBRDF) {
  44815. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44816. }
  44817. if (defines.TANGENT) {
  44818. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44819. }
  44820. if (defines.BUMP) {
  44821. fallbacks.addFallback(fallbackRank++, "BUMP");
  44822. }
  44823. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44824. if (defines.SPECULARTERM) {
  44825. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44826. }
  44827. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44828. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44829. }
  44830. if (defines.LIGHTMAP) {
  44831. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44832. }
  44833. if (defines.NORMAL) {
  44834. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44835. }
  44836. if (defines.AMBIENT) {
  44837. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44838. }
  44839. if (defines.EMISSIVE) {
  44840. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44841. }
  44842. if (defines.VERTEXCOLOR) {
  44843. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44844. }
  44845. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44846. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44847. }
  44848. if (defines.MORPHTARGETS) {
  44849. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44850. }
  44851. //Attributes
  44852. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44853. if (defines.NORMAL) {
  44854. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44855. }
  44856. if (defines.TANGENT) {
  44857. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44858. }
  44859. if (defines.UV1) {
  44860. attribs.push(BABYLON.VertexBuffer.UVKind);
  44861. }
  44862. if (defines.UV2) {
  44863. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44864. }
  44865. if (defines.VERTEXCOLOR) {
  44866. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44867. }
  44868. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44869. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44870. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44871. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44872. "vFogInfos", "vFogColor", "pointSize",
  44873. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44874. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44875. "mBones",
  44876. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44877. "vLightingIntensity",
  44878. "logarithmicDepthConstant",
  44879. "vSphericalX", "vSphericalY", "vSphericalZ",
  44880. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44881. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44882. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44883. "vTangentSpaceParams"
  44884. ];
  44885. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44886. "bumpSampler", "lightmapSampler", "opacitySampler",
  44887. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44888. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44889. "microSurfaceSampler", "environmentBrdfSampler"];
  44890. var uniformBuffers = ["Material", "Scene"];
  44891. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44892. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44893. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44894. uniformsNames: uniforms,
  44895. uniformBuffersNames: uniformBuffers,
  44896. samplers: samplers,
  44897. defines: defines,
  44898. maxSimultaneousLights: this._maxSimultaneousLights
  44899. });
  44900. var join = defines.toString();
  44901. return engine.createEffect("pbr", {
  44902. attributes: attribs,
  44903. uniformsNames: uniforms,
  44904. uniformBuffersNames: uniformBuffers,
  44905. samplers: samplers,
  44906. defines: join,
  44907. fallbacks: fallbacks,
  44908. onCompiled: onCompiled,
  44909. onError: onError,
  44910. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44911. }, engine);
  44912. };
  44913. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44914. if (useInstances === void 0) { useInstances = null; }
  44915. if (useClipPlane === void 0) { useClipPlane = null; }
  44916. var scene = this.getScene();
  44917. var engine = scene.getEngine();
  44918. // Lights
  44919. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44920. defines._needNormals = true;
  44921. // Textures
  44922. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44923. if (defines._areTexturesDirty) {
  44924. defines._needUVs = false;
  44925. if (scene.texturesEnabled) {
  44926. if (scene.getEngine().getCaps().textureLOD) {
  44927. defines.LODBASEDMICROSFURACE = true;
  44928. }
  44929. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44930. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44931. }
  44932. else {
  44933. defines.ALBEDO = false;
  44934. }
  44935. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44936. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44937. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44938. }
  44939. else {
  44940. defines.AMBIENT = false;
  44941. }
  44942. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44943. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44944. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44945. }
  44946. else {
  44947. defines.OPACITY = false;
  44948. }
  44949. var reflectionTexture = this._getReflectionTexture();
  44950. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44951. defines.REFLECTION = true;
  44952. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44953. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44954. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44955. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44956. defines.INVERTCUBICMAP = true;
  44957. }
  44958. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44959. switch (reflectionTexture.coordinatesMode) {
  44960. case BABYLON.Texture.EXPLICIT_MODE:
  44961. defines.REFLECTIONMAP_EXPLICIT = true;
  44962. break;
  44963. case BABYLON.Texture.PLANAR_MODE:
  44964. defines.REFLECTIONMAP_PLANAR = true;
  44965. break;
  44966. case BABYLON.Texture.PROJECTION_MODE:
  44967. defines.REFLECTIONMAP_PROJECTION = true;
  44968. break;
  44969. case BABYLON.Texture.SKYBOX_MODE:
  44970. defines.REFLECTIONMAP_SKYBOX = true;
  44971. break;
  44972. case BABYLON.Texture.SPHERICAL_MODE:
  44973. defines.REFLECTIONMAP_SPHERICAL = true;
  44974. break;
  44975. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44976. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44977. break;
  44978. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44979. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44980. break;
  44981. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44982. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44983. break;
  44984. case BABYLON.Texture.CUBIC_MODE:
  44985. case BABYLON.Texture.INVCUBIC_MODE:
  44986. default:
  44987. defines.REFLECTIONMAP_CUBIC = true;
  44988. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44989. break;
  44990. }
  44991. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44992. if (reflectionTexture.sphericalPolynomial) {
  44993. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44994. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44995. defines.USESPHERICALINVERTEX = false;
  44996. }
  44997. else {
  44998. defines.USESPHERICALINVERTEX = true;
  44999. }
  45000. }
  45001. }
  45002. }
  45003. else {
  45004. defines.REFLECTION = false;
  45005. defines.REFLECTIONMAP_3D = false;
  45006. defines.REFLECTIONMAP_SPHERICAL = false;
  45007. defines.REFLECTIONMAP_PLANAR = false;
  45008. defines.REFLECTIONMAP_CUBIC = false;
  45009. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45010. defines.REFLECTIONMAP_PROJECTION = false;
  45011. defines.REFLECTIONMAP_SKYBOX = false;
  45012. defines.REFLECTIONMAP_EXPLICIT = false;
  45013. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45014. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45015. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45016. defines.INVERTCUBICMAP = false;
  45017. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45018. defines.USESPHERICALINVERTEX = false;
  45019. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45020. defines.LODINREFLECTIONALPHA = false;
  45021. defines.GAMMAREFLECTION = false;
  45022. }
  45023. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45024. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45025. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45026. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45027. }
  45028. else {
  45029. defines.LIGHTMAP = false;
  45030. }
  45031. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45032. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45033. }
  45034. else {
  45035. defines.EMISSIVE = false;
  45036. }
  45037. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45038. if (this._metallicTexture) {
  45039. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45040. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45041. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45042. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45043. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45044. }
  45045. else if (this._reflectivityTexture) {
  45046. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45047. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45048. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45049. }
  45050. else {
  45051. defines.REFLECTIVITY = false;
  45052. }
  45053. if (this._microSurfaceTexture) {
  45054. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45055. }
  45056. else {
  45057. defines.MICROSURFACEMAP = false;
  45058. }
  45059. }
  45060. else {
  45061. defines.REFLECTIVITY = false;
  45062. defines.MICROSURFACEMAP = false;
  45063. }
  45064. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45066. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45067. defines.PARALLAX = true;
  45068. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45069. }
  45070. else {
  45071. defines.PARALLAX = false;
  45072. }
  45073. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45074. }
  45075. else {
  45076. defines.BUMP = false;
  45077. }
  45078. var refractionTexture = this._getRefractionTexture();
  45079. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45080. defines.REFRACTION = true;
  45081. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45082. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45083. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45084. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45085. if (this._linkRefractionWithTransparency) {
  45086. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45087. }
  45088. }
  45089. else {
  45090. defines.REFRACTION = false;
  45091. }
  45092. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45093. defines.ENVIRONMENTBRDF = true;
  45094. }
  45095. else {
  45096. defines.ENVIRONMENTBRDF = false;
  45097. }
  45098. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45099. defines.ALPHAFROMALBEDO = true;
  45100. }
  45101. else {
  45102. defines.ALPHAFROMALBEDO = false;
  45103. }
  45104. }
  45105. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45106. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45107. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45108. if (!this.backFaceCulling && this._twoSidedLighting) {
  45109. defines.TWOSIDEDLIGHTING = true;
  45110. }
  45111. else {
  45112. defines.TWOSIDEDLIGHTING = false;
  45113. }
  45114. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45115. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45116. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45117. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45118. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45119. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45120. }
  45121. if (defines._areImageProcessingDirty) {
  45122. this._imageProcessingConfiguration.prepareDefines(defines);
  45123. }
  45124. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45125. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45126. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45127. // Misc.
  45128. if (defines._areMiscDirty) {
  45129. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45130. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45131. }
  45132. // Values that need to be evaluated on every frame
  45133. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45134. // Attribs
  45135. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45136. };
  45137. /**
  45138. * Force shader compilation
  45139. */
  45140. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45141. var _this = this;
  45142. var localOptions = __assign({ clipPlane: false }, options);
  45143. var defines = new PBRMaterialDefines();
  45144. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45145. if (effect.isReady()) {
  45146. if (onCompiled) {
  45147. onCompiled(this);
  45148. }
  45149. }
  45150. else {
  45151. effect.onCompileObservable.add(function () {
  45152. if (onCompiled) {
  45153. onCompiled(_this);
  45154. }
  45155. });
  45156. }
  45157. };
  45158. /**
  45159. * Initializes the uniform buffer layout for the shader.
  45160. */
  45161. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45162. // Order is important !
  45163. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45164. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45165. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45166. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45167. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45168. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45169. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45170. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45171. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45172. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45173. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45174. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45175. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45176. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45177. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45178. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45179. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45180. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45181. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45182. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45183. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45184. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45185. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45186. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45187. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45188. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45189. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45190. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45191. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45192. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45193. this._uniformBuffer.addUniform("pointSize", 1);
  45194. this._uniformBuffer.create();
  45195. };
  45196. /**
  45197. * Unbinds the textures.
  45198. */
  45199. PBRBaseMaterial.prototype.unbind = function () {
  45200. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45201. this._uniformBuffer.setTexture("reflectionSampler", null);
  45202. }
  45203. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45204. this._uniformBuffer.setTexture("refractionSampler", null);
  45205. }
  45206. _super.prototype.unbind.call(this);
  45207. };
  45208. /**
  45209. * Binds the submesh data.
  45210. * @param world - The world matrix.
  45211. * @param mesh - The BJS mesh.
  45212. * @param subMesh - A submesh of the BJS mesh.
  45213. */
  45214. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45215. var scene = this.getScene();
  45216. var defines = subMesh._materialDefines;
  45217. if (!defines) {
  45218. return;
  45219. }
  45220. var effect = subMesh.effect;
  45221. if (!effect) {
  45222. return;
  45223. }
  45224. this._activeEffect = effect;
  45225. // Matrices
  45226. this.bindOnlyWorldMatrix(world);
  45227. // Normal Matrix
  45228. if (defines.OBJECTSPACE_NORMALMAP) {
  45229. world.toNormalMatrix(this._normalMatrix);
  45230. this.bindOnlyNormalMatrix(this._normalMatrix);
  45231. }
  45232. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45233. // Bones
  45234. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45235. var reflectionTexture = null;
  45236. if (mustRebind) {
  45237. this._uniformBuffer.bindToEffect(effect, "Material");
  45238. this.bindViewProjection(effect);
  45239. reflectionTexture = this._getReflectionTexture();
  45240. var refractionTexture = this._getRefractionTexture();
  45241. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45242. // Texture uniforms
  45243. if (scene.texturesEnabled) {
  45244. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45245. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45246. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45247. }
  45248. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45249. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45250. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45251. }
  45252. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45253. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45254. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45255. }
  45256. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45257. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45258. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45259. if (reflectionTexture.boundingBoxSize) {
  45260. var cubeTexture = reflectionTexture;
  45261. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45262. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45263. }
  45264. var polynomials = reflectionTexture.sphericalPolynomial;
  45265. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45266. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45267. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45268. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45269. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45270. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45271. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45272. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45273. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45274. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45275. }
  45276. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45277. }
  45278. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45279. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45280. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45281. }
  45282. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45283. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45284. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45285. }
  45286. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45287. if (this._metallicTexture) {
  45288. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45289. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45290. }
  45291. else if (this._reflectivityTexture) {
  45292. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45293. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45294. }
  45295. if (this._microSurfaceTexture) {
  45296. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45297. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45298. }
  45299. }
  45300. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45301. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45302. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45303. if (scene._mirroredCameraPosition) {
  45304. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45305. }
  45306. else {
  45307. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45308. }
  45309. }
  45310. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45311. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45312. var depth = 1.0;
  45313. if (!refractionTexture.isCube) {
  45314. if (refractionTexture.depth) {
  45315. depth = refractionTexture.depth;
  45316. }
  45317. }
  45318. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45319. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45320. }
  45321. }
  45322. // Point size
  45323. if (this.pointsCloud) {
  45324. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45325. }
  45326. // Colors
  45327. if (defines.METALLICWORKFLOW) {
  45328. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45329. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45330. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45331. }
  45332. else {
  45333. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45334. }
  45335. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45336. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45337. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45338. // Misc
  45339. this._lightingInfos.x = this._directIntensity;
  45340. this._lightingInfos.y = this._emissiveIntensity;
  45341. this._lightingInfos.z = this._environmentIntensity;
  45342. this._lightingInfos.w = this._specularIntensity;
  45343. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45344. }
  45345. // Textures
  45346. if (scene.texturesEnabled) {
  45347. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45348. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45349. }
  45350. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45351. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45352. }
  45353. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45354. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45355. }
  45356. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45357. if (defines.LODBASEDMICROSFURACE) {
  45358. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45359. }
  45360. else {
  45361. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45362. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45363. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45364. }
  45365. }
  45366. if (defines.ENVIRONMENTBRDF) {
  45367. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45368. }
  45369. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45370. if (defines.LODBASEDMICROSFURACE) {
  45371. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45372. }
  45373. else {
  45374. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45375. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45376. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45377. }
  45378. }
  45379. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45380. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45381. }
  45382. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45383. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45384. }
  45385. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45386. if (this._metallicTexture) {
  45387. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45388. }
  45389. else if (this._reflectivityTexture) {
  45390. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45391. }
  45392. if (this._microSurfaceTexture) {
  45393. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45394. }
  45395. }
  45396. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45397. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45398. }
  45399. }
  45400. // Clip plane
  45401. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45402. // Colors
  45403. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45404. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45405. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45406. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45407. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45408. }
  45409. if (mustRebind || !this.isFrozen) {
  45410. // Lights
  45411. if (scene.lightsEnabled && !this._disableLighting) {
  45412. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45413. }
  45414. // View
  45415. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45416. this.bindView(effect);
  45417. }
  45418. // Fog
  45419. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45420. // Morph targets
  45421. if (defines.NUM_MORPH_INFLUENCERS) {
  45422. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45423. }
  45424. // image processing
  45425. this._imageProcessingConfiguration.bind(this._activeEffect);
  45426. // Log. depth
  45427. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45428. }
  45429. this._uniformBuffer.update();
  45430. this._afterBind(mesh, this._activeEffect);
  45431. };
  45432. /**
  45433. * Returns the animatable textures.
  45434. * @returns - Array of animatable textures.
  45435. */
  45436. PBRBaseMaterial.prototype.getAnimatables = function () {
  45437. var results = [];
  45438. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45439. results.push(this._albedoTexture);
  45440. }
  45441. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45442. results.push(this._ambientTexture);
  45443. }
  45444. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45445. results.push(this._opacityTexture);
  45446. }
  45447. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45448. results.push(this._reflectionTexture);
  45449. }
  45450. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45451. results.push(this._emissiveTexture);
  45452. }
  45453. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45454. results.push(this._metallicTexture);
  45455. }
  45456. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45457. results.push(this._reflectivityTexture);
  45458. }
  45459. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45460. results.push(this._bumpTexture);
  45461. }
  45462. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45463. results.push(this._lightmapTexture);
  45464. }
  45465. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45466. results.push(this._refractionTexture);
  45467. }
  45468. return results;
  45469. };
  45470. /**
  45471. * Returns the texture used for reflections.
  45472. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45473. */
  45474. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45475. if (this._reflectionTexture) {
  45476. return this._reflectionTexture;
  45477. }
  45478. return this.getScene().environmentTexture;
  45479. };
  45480. /**
  45481. * Returns the texture used for refraction or null if none is used.
  45482. * @returns - Refection texture if present. If no refraction texture and refraction
  45483. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45484. */
  45485. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45486. if (this._refractionTexture) {
  45487. return this._refractionTexture;
  45488. }
  45489. if (this._linkRefractionWithTransparency) {
  45490. return this.getScene().environmentTexture;
  45491. }
  45492. return null;
  45493. };
  45494. /**
  45495. * Disposes the resources of the material.
  45496. * @param forceDisposeEffect - Forces the disposal of effects.
  45497. * @param forceDisposeTextures - Forces the disposal of all textures.
  45498. */
  45499. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45500. if (forceDisposeTextures) {
  45501. if (this._albedoTexture) {
  45502. this._albedoTexture.dispose();
  45503. }
  45504. if (this._ambientTexture) {
  45505. this._ambientTexture.dispose();
  45506. }
  45507. if (this._opacityTexture) {
  45508. this._opacityTexture.dispose();
  45509. }
  45510. if (this._reflectionTexture) {
  45511. this._reflectionTexture.dispose();
  45512. }
  45513. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45514. this._environmentBRDFTexture.dispose();
  45515. }
  45516. if (this._emissiveTexture) {
  45517. this._emissiveTexture.dispose();
  45518. }
  45519. if (this._metallicTexture) {
  45520. this._metallicTexture.dispose();
  45521. }
  45522. if (this._reflectivityTexture) {
  45523. this._reflectivityTexture.dispose();
  45524. }
  45525. if (this._bumpTexture) {
  45526. this._bumpTexture.dispose();
  45527. }
  45528. if (this._lightmapTexture) {
  45529. this._lightmapTexture.dispose();
  45530. }
  45531. if (this._refractionTexture) {
  45532. this._refractionTexture.dispose();
  45533. }
  45534. }
  45535. this._renderTargets.dispose();
  45536. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45537. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45538. }
  45539. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45540. };
  45541. /**
  45542. * Stores the reflectivity values based on metallic roughness workflow.
  45543. */
  45544. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45545. __decorate([
  45546. BABYLON.serializeAsImageProcessingConfiguration()
  45547. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45548. __decorate([
  45549. BABYLON.serialize()
  45550. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45551. __decorate([
  45552. BABYLON.serialize()
  45553. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45554. return PBRBaseMaterial;
  45555. }(BABYLON.PushMaterial));
  45556. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45557. })(BABYLON || (BABYLON = {}));
  45558. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45559. var BABYLON;
  45560. (function (BABYLON) {
  45561. /**
  45562. * The Physically based simple base material of BJS.
  45563. *
  45564. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45565. * It is used as the base class for both the specGloss and metalRough conventions.
  45566. */
  45567. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45568. __extends(PBRBaseSimpleMaterial, _super);
  45569. /**
  45570. * Instantiates a new PBRMaterial instance.
  45571. *
  45572. * @param name The material name
  45573. * @param scene The scene the material will be use in.
  45574. */
  45575. function PBRBaseSimpleMaterial(name, scene) {
  45576. var _this = _super.call(this, name, scene) || this;
  45577. /**
  45578. * Number of Simultaneous lights allowed on the material.
  45579. */
  45580. _this.maxSimultaneousLights = 4;
  45581. /**
  45582. * If sets to true, disables all the lights affecting the material.
  45583. */
  45584. _this.disableLighting = false;
  45585. /**
  45586. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45587. */
  45588. _this.invertNormalMapX = false;
  45589. /**
  45590. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45591. */
  45592. _this.invertNormalMapY = false;
  45593. /**
  45594. * Emissivie color used to self-illuminate the model.
  45595. */
  45596. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45597. /**
  45598. * Occlusion Channel Strenght.
  45599. */
  45600. _this.occlusionStrength = 1.0;
  45601. _this.useLightmapAsShadowmap = false;
  45602. _this._useAlphaFromAlbedoTexture = true;
  45603. _this._useAmbientInGrayScale = true;
  45604. return _this;
  45605. }
  45606. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45607. /**
  45608. * Gets the current double sided mode.
  45609. */
  45610. get: function () {
  45611. return this._twoSidedLighting;
  45612. },
  45613. /**
  45614. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45615. */
  45616. set: function (value) {
  45617. if (this._twoSidedLighting === value) {
  45618. return;
  45619. }
  45620. this._twoSidedLighting = value;
  45621. this.backFaceCulling = !value;
  45622. this._markAllSubMeshesAsTexturesDirty();
  45623. },
  45624. enumerable: true,
  45625. configurable: true
  45626. });
  45627. /**
  45628. * Return the active textures of the material.
  45629. */
  45630. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45631. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45632. if (this.environmentTexture) {
  45633. activeTextures.push(this.environmentTexture);
  45634. }
  45635. if (this.normalTexture) {
  45636. activeTextures.push(this.normalTexture);
  45637. }
  45638. if (this.emissiveTexture) {
  45639. activeTextures.push(this.emissiveTexture);
  45640. }
  45641. if (this.occlusionTexture) {
  45642. activeTextures.push(this.occlusionTexture);
  45643. }
  45644. if (this.lightmapTexture) {
  45645. activeTextures.push(this.lightmapTexture);
  45646. }
  45647. return activeTextures;
  45648. };
  45649. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45650. if (_super.prototype.hasTexture.call(this, texture)) {
  45651. return true;
  45652. }
  45653. if (this.lightmapTexture === texture) {
  45654. return true;
  45655. }
  45656. return false;
  45657. };
  45658. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45659. return "PBRBaseSimpleMaterial";
  45660. };
  45661. __decorate([
  45662. BABYLON.serialize(),
  45663. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45664. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45665. __decorate([
  45666. BABYLON.serialize(),
  45667. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45668. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45669. __decorate([
  45670. BABYLON.serializeAsTexture(),
  45671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45672. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45673. __decorate([
  45674. BABYLON.serialize(),
  45675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45676. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45677. __decorate([
  45678. BABYLON.serialize(),
  45679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45680. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45681. __decorate([
  45682. BABYLON.serializeAsTexture(),
  45683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45684. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45685. __decorate([
  45686. BABYLON.serializeAsColor3("emissive"),
  45687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45688. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45689. __decorate([
  45690. BABYLON.serializeAsTexture(),
  45691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45692. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45693. __decorate([
  45694. BABYLON.serialize(),
  45695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45696. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45697. __decorate([
  45698. BABYLON.serializeAsTexture(),
  45699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45700. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45701. __decorate([
  45702. BABYLON.serialize(),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45704. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45705. __decorate([
  45706. BABYLON.serialize()
  45707. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45708. __decorate([
  45709. BABYLON.serializeAsTexture(),
  45710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45711. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45712. __decorate([
  45713. BABYLON.serialize(),
  45714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45715. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45716. return PBRBaseSimpleMaterial;
  45717. }(BABYLON.PBRBaseMaterial));
  45718. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45719. })(BABYLON || (BABYLON = {}));
  45720. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45721. var BABYLON;
  45722. (function (BABYLON) {
  45723. /**
  45724. * The Physically based material of BJS.
  45725. *
  45726. * This offers the main features of a standard PBR material.
  45727. * For more information, please refer to the documentation :
  45728. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45729. */
  45730. var PBRMaterial = /** @class */ (function (_super) {
  45731. __extends(PBRMaterial, _super);
  45732. /**
  45733. * Instantiates a new PBRMaterial instance.
  45734. *
  45735. * @param name The material name
  45736. * @param scene The scene the material will be use in.
  45737. */
  45738. function PBRMaterial(name, scene) {
  45739. var _this = _super.call(this, name, scene) || this;
  45740. /**
  45741. * Intensity of the direct lights e.g. the four lights available in your scene.
  45742. * This impacts both the direct diffuse and specular highlights.
  45743. */
  45744. _this.directIntensity = 1.0;
  45745. /**
  45746. * Intensity of the emissive part of the material.
  45747. * This helps controlling the emissive effect without modifying the emissive color.
  45748. */
  45749. _this.emissiveIntensity = 1.0;
  45750. /**
  45751. * Intensity of the environment e.g. how much the environment will light the object
  45752. * either through harmonics for rough material or through the refelction for shiny ones.
  45753. */
  45754. _this.environmentIntensity = 1.0;
  45755. /**
  45756. * This is a special control allowing the reduction of the specular highlights coming from the
  45757. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45758. */
  45759. _this.specularIntensity = 1.0;
  45760. /**
  45761. * Debug Control allowing disabling the bump map on this material.
  45762. */
  45763. _this.disableBumpMap = false;
  45764. /**
  45765. * AKA Occlusion Texture Intensity in other nomenclature.
  45766. */
  45767. _this.ambientTextureStrength = 1.0;
  45768. /**
  45769. * The color of a material in ambient lighting.
  45770. */
  45771. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45772. /**
  45773. * AKA Diffuse Color in other nomenclature.
  45774. */
  45775. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45776. /**
  45777. * AKA Specular Color in other nomenclature.
  45778. */
  45779. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45780. /**
  45781. * The color reflected from the material.
  45782. */
  45783. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45784. /**
  45785. * The color emitted from the material.
  45786. */
  45787. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45788. /**
  45789. * AKA Glossiness in other nomenclature.
  45790. */
  45791. _this.microSurface = 1.0;
  45792. /**
  45793. * source material index of refraction (IOR)' / 'destination material IOR.
  45794. */
  45795. _this.indexOfRefraction = 0.66;
  45796. /**
  45797. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45798. */
  45799. _this.invertRefractionY = false;
  45800. /**
  45801. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45802. * Materials half opaque for instance using refraction could benefit from this control.
  45803. */
  45804. _this.linkRefractionWithTransparency = false;
  45805. _this.useLightmapAsShadowmap = false;
  45806. /**
  45807. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45808. */
  45809. _this.useAlphaFromAlbedoTexture = false;
  45810. /**
  45811. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45812. */
  45813. _this.forceAlphaTest = false;
  45814. /**
  45815. * Defines the alpha limits in alpha test mode.
  45816. */
  45817. _this.alphaCutOff = 0.4;
  45818. /**
  45819. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45820. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45821. */
  45822. _this.useSpecularOverAlpha = true;
  45823. /**
  45824. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45825. */
  45826. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45827. /**
  45828. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45829. */
  45830. _this.useRoughnessFromMetallicTextureAlpha = true;
  45831. /**
  45832. * Specifies if the metallic texture contains the roughness information in its green channel.
  45833. */
  45834. _this.useRoughnessFromMetallicTextureGreen = false;
  45835. /**
  45836. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45837. */
  45838. _this.useMetallnessFromMetallicTextureBlue = false;
  45839. /**
  45840. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45841. */
  45842. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45843. /**
  45844. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45845. */
  45846. _this.useAmbientInGrayScale = false;
  45847. /**
  45848. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45849. * The material will try to infer what glossiness each pixel should be.
  45850. */
  45851. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45852. /**
  45853. * BJS is using an harcoded light falloff based on a manually sets up range.
  45854. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45855. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45856. */
  45857. _this.usePhysicalLightFalloff = true;
  45858. /**
  45859. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45860. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45861. */
  45862. _this.useRadianceOverAlpha = true;
  45863. /**
  45864. * Allows using an object space normal map (instead of tangent space).
  45865. */
  45866. _this.useObjectSpaceNormalMap = false;
  45867. /**
  45868. * Allows using the bump map in parallax mode.
  45869. */
  45870. _this.useParallax = false;
  45871. /**
  45872. * Allows using the bump map in parallax occlusion mode.
  45873. */
  45874. _this.useParallaxOcclusion = false;
  45875. /**
  45876. * Controls the scale bias of the parallax mode.
  45877. */
  45878. _this.parallaxScaleBias = 0.05;
  45879. /**
  45880. * If sets to true, disables all the lights affecting the material.
  45881. */
  45882. _this.disableLighting = false;
  45883. /**
  45884. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45885. */
  45886. _this.forceIrradianceInFragment = false;
  45887. /**
  45888. * Number of Simultaneous lights allowed on the material.
  45889. */
  45890. _this.maxSimultaneousLights = 4;
  45891. /**
  45892. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45893. */
  45894. _this.invertNormalMapX = false;
  45895. /**
  45896. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45897. */
  45898. _this.invertNormalMapY = false;
  45899. /**
  45900. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45901. */
  45902. _this.twoSidedLighting = false;
  45903. /**
  45904. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45905. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45906. */
  45907. _this.useAlphaFresnel = false;
  45908. /**
  45909. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45910. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45911. */
  45912. _this.useLinearAlphaFresnel = false;
  45913. /**
  45914. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45915. * And/Or occlude the blended part.
  45916. */
  45917. _this.environmentBRDFTexture = null;
  45918. /**
  45919. * Force normal to face away from face.
  45920. */
  45921. _this.forceNormalForward = false;
  45922. /**
  45923. * Enables specular anti aliasing in the PBR shader.
  45924. * It will both interacts on the Geometry for analytical and IBL lighting.
  45925. * It also prefilter the roughness map based on the bump values.
  45926. */
  45927. _this.enableSpecularAntiAliasing = false;
  45928. /**
  45929. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45930. * makes the reflect vector face the model (under horizon).
  45931. */
  45932. _this.useHorizonOcclusion = true;
  45933. /**
  45934. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45935. * too much the area relying on ambient texture to define their ambient occlusion.
  45936. */
  45937. _this.useRadianceOcclusion = true;
  45938. /**
  45939. * If set to true, no lighting calculations will be applied.
  45940. */
  45941. _this.unlit = false;
  45942. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45943. return _this;
  45944. }
  45945. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45946. /**
  45947. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45948. */
  45949. get: function () {
  45950. return this._PBRMATERIAL_OPAQUE;
  45951. },
  45952. enumerable: true,
  45953. configurable: true
  45954. });
  45955. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45956. /**
  45957. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45958. */
  45959. get: function () {
  45960. return this._PBRMATERIAL_ALPHATEST;
  45961. },
  45962. enumerable: true,
  45963. configurable: true
  45964. });
  45965. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45966. /**
  45967. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45968. */
  45969. get: function () {
  45970. return this._PBRMATERIAL_ALPHABLEND;
  45971. },
  45972. enumerable: true,
  45973. configurable: true
  45974. });
  45975. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45976. /**
  45977. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45978. * They are also discarded below the alpha cutoff threshold to improve performances.
  45979. */
  45980. get: function () {
  45981. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45982. },
  45983. enumerable: true,
  45984. configurable: true
  45985. });
  45986. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45987. /**
  45988. * Gets the image processing configuration used either in this material.
  45989. */
  45990. get: function () {
  45991. return this._imageProcessingConfiguration;
  45992. },
  45993. /**
  45994. * Sets the Default image processing configuration used either in the this material.
  45995. *
  45996. * If sets to null, the scene one is in use.
  45997. */
  45998. set: function (value) {
  45999. this._attachImageProcessingConfiguration(value);
  46000. // Ensure the effect will be rebuilt.
  46001. this._markAllSubMeshesAsTexturesDirty();
  46002. },
  46003. enumerable: true,
  46004. configurable: true
  46005. });
  46006. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46007. /**
  46008. * Gets wether the color curves effect is enabled.
  46009. */
  46010. get: function () {
  46011. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46012. },
  46013. /**
  46014. * Sets wether the color curves effect is enabled.
  46015. */
  46016. set: function (value) {
  46017. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46018. },
  46019. enumerable: true,
  46020. configurable: true
  46021. });
  46022. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46023. /**
  46024. * Gets wether the color grading effect is enabled.
  46025. */
  46026. get: function () {
  46027. return this.imageProcessingConfiguration.colorGradingEnabled;
  46028. },
  46029. /**
  46030. * Gets wether the color grading effect is enabled.
  46031. */
  46032. set: function (value) {
  46033. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46034. },
  46035. enumerable: true,
  46036. configurable: true
  46037. });
  46038. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46039. /**
  46040. * Gets wether tonemapping is enabled or not.
  46041. */
  46042. get: function () {
  46043. return this._imageProcessingConfiguration.toneMappingEnabled;
  46044. },
  46045. /**
  46046. * Sets wether tonemapping is enabled or not
  46047. */
  46048. set: function (value) {
  46049. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46050. },
  46051. enumerable: true,
  46052. configurable: true
  46053. });
  46054. ;
  46055. ;
  46056. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46057. /**
  46058. * The camera exposure used on this material.
  46059. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46060. * This corresponds to a photographic exposure.
  46061. */
  46062. get: function () {
  46063. return this._imageProcessingConfiguration.exposure;
  46064. },
  46065. /**
  46066. * The camera exposure used on this material.
  46067. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46068. * This corresponds to a photographic exposure.
  46069. */
  46070. set: function (value) {
  46071. this._imageProcessingConfiguration.exposure = value;
  46072. },
  46073. enumerable: true,
  46074. configurable: true
  46075. });
  46076. ;
  46077. ;
  46078. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46079. /**
  46080. * Gets The camera contrast used on this material.
  46081. */
  46082. get: function () {
  46083. return this._imageProcessingConfiguration.contrast;
  46084. },
  46085. /**
  46086. * Sets The camera contrast used on this material.
  46087. */
  46088. set: function (value) {
  46089. this._imageProcessingConfiguration.contrast = value;
  46090. },
  46091. enumerable: true,
  46092. configurable: true
  46093. });
  46094. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46095. /**
  46096. * Gets the Color Grading 2D Lookup Texture.
  46097. */
  46098. get: function () {
  46099. return this._imageProcessingConfiguration.colorGradingTexture;
  46100. },
  46101. /**
  46102. * Sets the Color Grading 2D Lookup Texture.
  46103. */
  46104. set: function (value) {
  46105. this._imageProcessingConfiguration.colorGradingTexture = value;
  46106. },
  46107. enumerable: true,
  46108. configurable: true
  46109. });
  46110. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46111. /**
  46112. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46113. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46114. * 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;
  46115. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46116. */
  46117. get: function () {
  46118. return this._imageProcessingConfiguration.colorCurves;
  46119. },
  46120. /**
  46121. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46122. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46123. * 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;
  46124. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46125. */
  46126. set: function (value) {
  46127. this._imageProcessingConfiguration.colorCurves = value;
  46128. },
  46129. enumerable: true,
  46130. configurable: true
  46131. });
  46132. /**
  46133. * Returns the name of this material class.
  46134. */
  46135. PBRMaterial.prototype.getClassName = function () {
  46136. return "PBRMaterial";
  46137. };
  46138. /**
  46139. * Returns an array of the actively used textures.
  46140. * @returns - Array of BaseTextures
  46141. */
  46142. PBRMaterial.prototype.getActiveTextures = function () {
  46143. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46144. if (this._albedoTexture) {
  46145. activeTextures.push(this._albedoTexture);
  46146. }
  46147. if (this._ambientTexture) {
  46148. activeTextures.push(this._ambientTexture);
  46149. }
  46150. if (this._opacityTexture) {
  46151. activeTextures.push(this._opacityTexture);
  46152. }
  46153. if (this._reflectionTexture) {
  46154. activeTextures.push(this._reflectionTexture);
  46155. }
  46156. if (this._emissiveTexture) {
  46157. activeTextures.push(this._emissiveTexture);
  46158. }
  46159. if (this._reflectivityTexture) {
  46160. activeTextures.push(this._reflectivityTexture);
  46161. }
  46162. if (this._metallicTexture) {
  46163. activeTextures.push(this._metallicTexture);
  46164. }
  46165. if (this._microSurfaceTexture) {
  46166. activeTextures.push(this._microSurfaceTexture);
  46167. }
  46168. if (this._bumpTexture) {
  46169. activeTextures.push(this._bumpTexture);
  46170. }
  46171. if (this._lightmapTexture) {
  46172. activeTextures.push(this._lightmapTexture);
  46173. }
  46174. if (this._refractionTexture) {
  46175. activeTextures.push(this._refractionTexture);
  46176. }
  46177. return activeTextures;
  46178. };
  46179. /**
  46180. * Checks to see if a texture is used in the material.
  46181. * @param texture - Base texture to use.
  46182. * @returns - Boolean specifying if a texture is used in the material.
  46183. */
  46184. PBRMaterial.prototype.hasTexture = function (texture) {
  46185. if (_super.prototype.hasTexture.call(this, texture)) {
  46186. return true;
  46187. }
  46188. if (this._albedoTexture === texture) {
  46189. return true;
  46190. }
  46191. if (this._ambientTexture === texture) {
  46192. return true;
  46193. }
  46194. if (this._opacityTexture === texture) {
  46195. return true;
  46196. }
  46197. if (this._reflectionTexture === texture) {
  46198. return true;
  46199. }
  46200. if (this._reflectivityTexture === texture) {
  46201. return true;
  46202. }
  46203. if (this._metallicTexture === texture) {
  46204. return true;
  46205. }
  46206. if (this._microSurfaceTexture === texture) {
  46207. return true;
  46208. }
  46209. if (this._bumpTexture === texture) {
  46210. return true;
  46211. }
  46212. if (this._lightmapTexture === texture) {
  46213. return true;
  46214. }
  46215. if (this._refractionTexture === texture) {
  46216. return true;
  46217. }
  46218. return false;
  46219. };
  46220. /**
  46221. * Makes a duplicate of the current material.
  46222. * @param name - name to use for the new material.
  46223. */
  46224. PBRMaterial.prototype.clone = function (name) {
  46225. var _this = this;
  46226. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46227. clone.id = name;
  46228. clone.name = name;
  46229. return clone;
  46230. };
  46231. /**
  46232. * Serializes this PBR Material.
  46233. * @returns - An object with the serialized material.
  46234. */
  46235. PBRMaterial.prototype.serialize = function () {
  46236. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46237. serializationObject.customType = "BABYLON.PBRMaterial";
  46238. return serializationObject;
  46239. };
  46240. // Statics
  46241. /**
  46242. * Parses a PBR Material from a serialized object.
  46243. * @param source - Serialized object.
  46244. * @param scene - BJS scene instance.
  46245. * @param rootUrl - url for the scene object
  46246. * @returns - PBRMaterial
  46247. */
  46248. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46249. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46250. };
  46251. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46252. /**
  46253. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46254. */
  46255. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46256. /**
  46257. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46258. */
  46259. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46260. /**
  46261. * 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.
  46262. * They are also discarded below the alpha cutoff threshold to improve performances.
  46263. */
  46264. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46265. __decorate([
  46266. BABYLON.serialize(),
  46267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46268. ], PBRMaterial.prototype, "directIntensity", void 0);
  46269. __decorate([
  46270. BABYLON.serialize(),
  46271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46272. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46273. __decorate([
  46274. BABYLON.serialize(),
  46275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46276. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46277. __decorate([
  46278. BABYLON.serialize(),
  46279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46280. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46281. __decorate([
  46282. BABYLON.serialize(),
  46283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46284. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46285. __decorate([
  46286. BABYLON.serializeAsTexture(),
  46287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46288. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46289. __decorate([
  46290. BABYLON.serializeAsTexture(),
  46291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46292. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46293. __decorate([
  46294. BABYLON.serialize(),
  46295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46296. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46297. __decorate([
  46298. BABYLON.serializeAsTexture(),
  46299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46300. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46301. __decorate([
  46302. BABYLON.serializeAsTexture(),
  46303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46304. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46305. __decorate([
  46306. BABYLON.serializeAsTexture(),
  46307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46308. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46309. __decorate([
  46310. BABYLON.serializeAsTexture(),
  46311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46312. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46313. __decorate([
  46314. BABYLON.serializeAsTexture(),
  46315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46316. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46317. __decorate([
  46318. BABYLON.serialize(),
  46319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46320. ], PBRMaterial.prototype, "metallic", void 0);
  46321. __decorate([
  46322. BABYLON.serialize(),
  46323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46324. ], PBRMaterial.prototype, "roughness", void 0);
  46325. __decorate([
  46326. BABYLON.serializeAsTexture(),
  46327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46328. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46329. __decorate([
  46330. BABYLON.serializeAsTexture(),
  46331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46332. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46333. __decorate([
  46334. BABYLON.serializeAsTexture(),
  46335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46336. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46337. __decorate([
  46338. BABYLON.serializeAsTexture(),
  46339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46340. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46341. __decorate([
  46342. BABYLON.serializeAsColor3("ambient"),
  46343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46344. ], PBRMaterial.prototype, "ambientColor", void 0);
  46345. __decorate([
  46346. BABYLON.serializeAsColor3("albedo"),
  46347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46348. ], PBRMaterial.prototype, "albedoColor", void 0);
  46349. __decorate([
  46350. BABYLON.serializeAsColor3("reflectivity"),
  46351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46352. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46353. __decorate([
  46354. BABYLON.serializeAsColor3("reflection"),
  46355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46356. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46357. __decorate([
  46358. BABYLON.serializeAsColor3("emissive"),
  46359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46360. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46361. __decorate([
  46362. BABYLON.serialize(),
  46363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46364. ], PBRMaterial.prototype, "microSurface", void 0);
  46365. __decorate([
  46366. BABYLON.serialize(),
  46367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46368. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46369. __decorate([
  46370. BABYLON.serialize(),
  46371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46372. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46373. __decorate([
  46374. BABYLON.serialize(),
  46375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46376. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46377. __decorate([
  46378. BABYLON.serialize(),
  46379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46380. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46381. __decorate([
  46382. BABYLON.serialize(),
  46383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46384. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46385. __decorate([
  46386. BABYLON.serialize(),
  46387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46388. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46389. __decorate([
  46390. BABYLON.serialize(),
  46391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46392. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46393. __decorate([
  46394. BABYLON.serialize(),
  46395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46396. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46397. __decorate([
  46398. BABYLON.serialize(),
  46399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46400. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46401. __decorate([
  46402. BABYLON.serialize(),
  46403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46404. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46405. __decorate([
  46406. BABYLON.serialize(),
  46407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46408. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46409. __decorate([
  46410. BABYLON.serialize(),
  46411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46412. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46413. __decorate([
  46414. BABYLON.serialize(),
  46415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46416. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46417. __decorate([
  46418. BABYLON.serialize(),
  46419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46420. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46421. __decorate([
  46422. BABYLON.serialize(),
  46423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46424. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46425. __decorate([
  46426. BABYLON.serialize(),
  46427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46428. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46429. __decorate([
  46430. BABYLON.serialize(),
  46431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46432. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46433. __decorate([
  46434. BABYLON.serialize(),
  46435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46436. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46437. __decorate([
  46438. BABYLON.serialize(),
  46439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46440. ], PBRMaterial.prototype, "useParallax", void 0);
  46441. __decorate([
  46442. BABYLON.serialize(),
  46443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46444. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46445. __decorate([
  46446. BABYLON.serialize(),
  46447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46448. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46449. __decorate([
  46450. BABYLON.serialize(),
  46451. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46452. ], PBRMaterial.prototype, "disableLighting", void 0);
  46453. __decorate([
  46454. BABYLON.serialize(),
  46455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46456. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46457. __decorate([
  46458. BABYLON.serialize(),
  46459. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46460. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46461. __decorate([
  46462. BABYLON.serialize(),
  46463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46464. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46465. __decorate([
  46466. BABYLON.serialize(),
  46467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46468. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46469. __decorate([
  46470. BABYLON.serialize(),
  46471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46472. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46473. __decorate([
  46474. BABYLON.serialize(),
  46475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46476. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46477. __decorate([
  46478. BABYLON.serialize(),
  46479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46480. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46481. __decorate([
  46482. BABYLON.serializeAsTexture(),
  46483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46484. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46485. __decorate([
  46486. BABYLON.serialize(),
  46487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46488. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46489. __decorate([
  46490. BABYLON.serialize(),
  46491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46492. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46493. __decorate([
  46494. BABYLON.serialize(),
  46495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46496. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46497. __decorate([
  46498. BABYLON.serialize(),
  46499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46500. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46501. __decorate([
  46502. BABYLON.serialize(),
  46503. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46504. ], PBRMaterial.prototype, "unlit", void 0);
  46505. return PBRMaterial;
  46506. }(BABYLON.PBRBaseMaterial));
  46507. BABYLON.PBRMaterial = PBRMaterial;
  46508. })(BABYLON || (BABYLON = {}));
  46509. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46510. var BABYLON;
  46511. (function (BABYLON) {
  46512. /**
  46513. * The PBR material of BJS following the metal roughness convention.
  46514. *
  46515. * This fits to the PBR convention in the GLTF definition:
  46516. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46517. */
  46518. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46519. __extends(PBRMetallicRoughnessMaterial, _super);
  46520. /**
  46521. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46522. *
  46523. * @param name The material name
  46524. * @param scene The scene the material will be use in.
  46525. */
  46526. function PBRMetallicRoughnessMaterial(name, scene) {
  46527. var _this = _super.call(this, name, scene) || this;
  46528. _this._useRoughnessFromMetallicTextureAlpha = false;
  46529. _this._useRoughnessFromMetallicTextureGreen = true;
  46530. _this._useMetallnessFromMetallicTextureBlue = true;
  46531. _this.metallic = 1.0;
  46532. _this.roughness = 1.0;
  46533. return _this;
  46534. }
  46535. /**
  46536. * Return the currrent class name of the material.
  46537. */
  46538. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46539. return "PBRMetallicRoughnessMaterial";
  46540. };
  46541. /**
  46542. * Return the active textures of the material.
  46543. */
  46544. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46545. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46546. if (this.baseTexture) {
  46547. activeTextures.push(this.baseTexture);
  46548. }
  46549. if (this.metallicRoughnessTexture) {
  46550. activeTextures.push(this.metallicRoughnessTexture);
  46551. }
  46552. return activeTextures;
  46553. };
  46554. /**
  46555. * Checks to see if a texture is used in the material.
  46556. * @param texture - Base texture to use.
  46557. * @returns - Boolean specifying if a texture is used in the material.
  46558. */
  46559. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46560. if (_super.prototype.hasTexture.call(this, texture)) {
  46561. return true;
  46562. }
  46563. if (this.baseTexture === texture) {
  46564. return true;
  46565. }
  46566. if (this.metallicRoughnessTexture === texture) {
  46567. return true;
  46568. }
  46569. return false;
  46570. };
  46571. /**
  46572. * Makes a duplicate of the current material.
  46573. * @param name - name to use for the new material.
  46574. */
  46575. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46576. var _this = this;
  46577. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46578. clone.id = name;
  46579. clone.name = name;
  46580. return clone;
  46581. };
  46582. /**
  46583. * Serialize the material to a parsable JSON object.
  46584. */
  46585. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46586. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46587. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46588. return serializationObject;
  46589. };
  46590. /**
  46591. * Parses a JSON object correponding to the serialize function.
  46592. */
  46593. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46594. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46595. };
  46596. __decorate([
  46597. BABYLON.serializeAsColor3(),
  46598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46599. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46600. __decorate([
  46601. BABYLON.serializeAsTexture(),
  46602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46603. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46604. __decorate([
  46605. BABYLON.serialize(),
  46606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46607. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46608. __decorate([
  46609. BABYLON.serialize(),
  46610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46611. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46612. __decorate([
  46613. BABYLON.serializeAsTexture(),
  46614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46615. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46616. return PBRMetallicRoughnessMaterial;
  46617. }(BABYLON.PBRBaseSimpleMaterial));
  46618. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46619. })(BABYLON || (BABYLON = {}));
  46620. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46621. var BABYLON;
  46622. (function (BABYLON) {
  46623. /**
  46624. * The PBR material of BJS following the specular glossiness convention.
  46625. *
  46626. * This fits to the PBR convention in the GLTF definition:
  46627. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46628. */
  46629. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46630. __extends(PBRSpecularGlossinessMaterial, _super);
  46631. /**
  46632. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46633. *
  46634. * @param name The material name
  46635. * @param scene The scene the material will be use in.
  46636. */
  46637. function PBRSpecularGlossinessMaterial(name, scene) {
  46638. var _this = _super.call(this, name, scene) || this;
  46639. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46640. return _this;
  46641. }
  46642. /**
  46643. * Return the currrent class name of the material.
  46644. */
  46645. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46646. return "PBRSpecularGlossinessMaterial";
  46647. };
  46648. /**
  46649. * Return the active textures of the material.
  46650. */
  46651. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46652. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46653. if (this.diffuseTexture) {
  46654. activeTextures.push(this.diffuseTexture);
  46655. }
  46656. if (this.specularGlossinessTexture) {
  46657. activeTextures.push(this.specularGlossinessTexture);
  46658. }
  46659. return activeTextures;
  46660. };
  46661. /**
  46662. * Checks to see if a texture is used in the material.
  46663. * @param texture - Base texture to use.
  46664. * @returns - Boolean specifying if a texture is used in the material.
  46665. */
  46666. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46667. if (_super.prototype.hasTexture.call(this, texture)) {
  46668. return true;
  46669. }
  46670. if (this.diffuseTexture === texture) {
  46671. return true;
  46672. }
  46673. if (this.specularGlossinessTexture === texture) {
  46674. return true;
  46675. }
  46676. return false;
  46677. };
  46678. /**
  46679. * Makes a duplicate of the current material.
  46680. * @param name - name to use for the new material.
  46681. */
  46682. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46683. var _this = this;
  46684. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46685. clone.id = name;
  46686. clone.name = name;
  46687. return clone;
  46688. };
  46689. /**
  46690. * Serialize the material to a parsable JSON object.
  46691. */
  46692. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46693. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46694. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46695. return serializationObject;
  46696. };
  46697. /**
  46698. * Parses a JSON object correponding to the serialize function.
  46699. */
  46700. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46701. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46702. };
  46703. __decorate([
  46704. BABYLON.serializeAsColor3("diffuse"),
  46705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46706. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46707. __decorate([
  46708. BABYLON.serializeAsTexture(),
  46709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46710. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46711. __decorate([
  46712. BABYLON.serializeAsColor3("specular"),
  46713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46714. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46715. __decorate([
  46716. BABYLON.serialize(),
  46717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46718. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46719. __decorate([
  46720. BABYLON.serializeAsTexture(),
  46721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46722. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46723. return PBRSpecularGlossinessMaterial;
  46724. }(BABYLON.PBRBaseSimpleMaterial));
  46725. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46726. })(BABYLON || (BABYLON = {}));
  46727. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46728. var BABYLON;
  46729. (function (BABYLON) {
  46730. BABYLON.CameraInputTypes = {};
  46731. var CameraInputsManager = /** @class */ (function () {
  46732. function CameraInputsManager(camera) {
  46733. this.attached = {};
  46734. this.camera = camera;
  46735. this.checkInputs = function () { };
  46736. }
  46737. /**
  46738. * Add an input method to a camera.
  46739. * builtin inputs example: camera.inputs.addGamepad();
  46740. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46741. * @param input camera input method
  46742. */
  46743. CameraInputsManager.prototype.add = function (input) {
  46744. var type = input.getSimpleName();
  46745. if (this.attached[type]) {
  46746. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46747. return;
  46748. }
  46749. this.attached[type] = input;
  46750. input.camera = this.camera;
  46751. //for checkInputs, we are dynamically creating a function
  46752. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46753. if (input.checkInputs) {
  46754. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46755. }
  46756. if (this.attachedElement) {
  46757. input.attachControl(this.attachedElement);
  46758. }
  46759. };
  46760. /**
  46761. * Remove a specific input method from a camera
  46762. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46763. * @param inputToRemove camera input method
  46764. */
  46765. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46766. for (var cam in this.attached) {
  46767. var input = this.attached[cam];
  46768. if (input === inputToRemove) {
  46769. input.detachControl(this.attachedElement);
  46770. input.camera = null;
  46771. delete this.attached[cam];
  46772. this.rebuildInputCheck();
  46773. }
  46774. }
  46775. };
  46776. CameraInputsManager.prototype.removeByType = function (inputType) {
  46777. for (var cam in this.attached) {
  46778. var input = this.attached[cam];
  46779. if (input.getClassName() === inputType) {
  46780. input.detachControl(this.attachedElement);
  46781. input.camera = null;
  46782. delete this.attached[cam];
  46783. this.rebuildInputCheck();
  46784. }
  46785. }
  46786. };
  46787. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46788. var current = this.checkInputs;
  46789. return function () {
  46790. current();
  46791. fn();
  46792. };
  46793. };
  46794. CameraInputsManager.prototype.attachInput = function (input) {
  46795. if (this.attachedElement) {
  46796. input.attachControl(this.attachedElement, this.noPreventDefault);
  46797. }
  46798. };
  46799. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46800. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46801. if (this.attachedElement) {
  46802. return;
  46803. }
  46804. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46805. this.attachedElement = element;
  46806. this.noPreventDefault = noPreventDefault;
  46807. for (var cam in this.attached) {
  46808. this.attached[cam].attachControl(element, noPreventDefault);
  46809. }
  46810. };
  46811. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46812. if (disconnect === void 0) { disconnect = false; }
  46813. if (this.attachedElement !== element) {
  46814. return;
  46815. }
  46816. for (var cam in this.attached) {
  46817. this.attached[cam].detachControl(element);
  46818. if (disconnect) {
  46819. this.attached[cam].camera = null;
  46820. }
  46821. }
  46822. this.attachedElement = null;
  46823. };
  46824. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46825. this.checkInputs = function () { };
  46826. for (var cam in this.attached) {
  46827. var input = this.attached[cam];
  46828. if (input.checkInputs) {
  46829. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46830. }
  46831. }
  46832. };
  46833. /**
  46834. * Remove all attached input methods from a camera
  46835. */
  46836. CameraInputsManager.prototype.clear = function () {
  46837. if (this.attachedElement) {
  46838. this.detachElement(this.attachedElement, true);
  46839. }
  46840. this.attached = {};
  46841. this.attachedElement = null;
  46842. this.checkInputs = function () { };
  46843. };
  46844. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46845. var inputs = {};
  46846. for (var cam in this.attached) {
  46847. var input = this.attached[cam];
  46848. var res = BABYLON.SerializationHelper.Serialize(input);
  46849. inputs[input.getClassName()] = res;
  46850. }
  46851. serializedCamera.inputsmgr = inputs;
  46852. };
  46853. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46854. var parsedInputs = parsedCamera.inputsmgr;
  46855. if (parsedInputs) {
  46856. this.clear();
  46857. for (var n in parsedInputs) {
  46858. var construct = BABYLON.CameraInputTypes[n];
  46859. if (construct) {
  46860. var parsedinput = parsedInputs[n];
  46861. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46862. this.add(input);
  46863. }
  46864. }
  46865. }
  46866. else {
  46867. //2016-03-08 this part is for managing backward compatibility
  46868. for (var n in this.attached) {
  46869. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46870. if (construct) {
  46871. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46872. this.remove(this.attached[n]);
  46873. this.add(input);
  46874. }
  46875. }
  46876. }
  46877. };
  46878. return CameraInputsManager;
  46879. }());
  46880. BABYLON.CameraInputsManager = CameraInputsManager;
  46881. })(BABYLON || (BABYLON = {}));
  46882. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46883. var BABYLON;
  46884. (function (BABYLON) {
  46885. var TargetCamera = /** @class */ (function (_super) {
  46886. __extends(TargetCamera, _super);
  46887. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46888. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46889. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46890. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46891. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46892. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46893. _this.speed = 2.0;
  46894. _this.noRotationConstraint = false;
  46895. _this.lockedTarget = null;
  46896. _this._currentTarget = BABYLON.Vector3.Zero();
  46897. _this._viewMatrix = BABYLON.Matrix.Zero();
  46898. _this._camMatrix = BABYLON.Matrix.Zero();
  46899. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46900. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46901. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46902. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46903. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46904. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46905. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46906. return _this;
  46907. }
  46908. TargetCamera.prototype.getFrontPosition = function (distance) {
  46909. this.getWorldMatrix();
  46910. var direction = this.getTarget().subtract(this.position);
  46911. direction.normalize();
  46912. direction.scaleInPlace(distance);
  46913. return this.globalPosition.add(direction);
  46914. };
  46915. TargetCamera.prototype._getLockedTargetPosition = function () {
  46916. if (!this.lockedTarget) {
  46917. return null;
  46918. }
  46919. if (this.lockedTarget.absolutePosition) {
  46920. this.lockedTarget.computeWorldMatrix();
  46921. }
  46922. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46923. };
  46924. TargetCamera.prototype.storeState = function () {
  46925. this._storedPosition = this.position.clone();
  46926. this._storedRotation = this.rotation.clone();
  46927. if (this.rotationQuaternion) {
  46928. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46929. }
  46930. return _super.prototype.storeState.call(this);
  46931. };
  46932. /**
  46933. * Restored camera state. You must call storeState() first
  46934. */
  46935. TargetCamera.prototype._restoreStateValues = function () {
  46936. if (!_super.prototype._restoreStateValues.call(this)) {
  46937. return false;
  46938. }
  46939. this.position = this._storedPosition.clone();
  46940. this.rotation = this._storedRotation.clone();
  46941. if (this.rotationQuaternion) {
  46942. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46943. }
  46944. this.cameraDirection.copyFromFloats(0, 0, 0);
  46945. this.cameraRotation.copyFromFloats(0, 0);
  46946. return true;
  46947. };
  46948. // Cache
  46949. TargetCamera.prototype._initCache = function () {
  46950. _super.prototype._initCache.call(this);
  46951. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46952. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46953. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46954. };
  46955. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46956. if (!ignoreParentClass) {
  46957. _super.prototype._updateCache.call(this);
  46958. }
  46959. var lockedTargetPosition = this._getLockedTargetPosition();
  46960. if (!lockedTargetPosition) {
  46961. this._cache.lockedTarget = null;
  46962. }
  46963. else {
  46964. if (!this._cache.lockedTarget) {
  46965. this._cache.lockedTarget = lockedTargetPosition.clone();
  46966. }
  46967. else {
  46968. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46969. }
  46970. }
  46971. this._cache.rotation.copyFrom(this.rotation);
  46972. if (this.rotationQuaternion)
  46973. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46974. };
  46975. // Synchronized
  46976. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46977. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46978. return false;
  46979. }
  46980. var lockedTargetPosition = this._getLockedTargetPosition();
  46981. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46982. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46983. };
  46984. // Methods
  46985. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46986. var engine = this.getEngine();
  46987. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46988. };
  46989. // Target
  46990. TargetCamera.prototype.setTarget = function (target) {
  46991. this.upVector.normalize();
  46992. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46993. this._camMatrix.invert();
  46994. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46995. var vDir = target.subtract(this.position);
  46996. if (vDir.x >= 0.0) {
  46997. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46998. }
  46999. else {
  47000. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47001. }
  47002. this.rotation.z = 0;
  47003. if (isNaN(this.rotation.x)) {
  47004. this.rotation.x = 0;
  47005. }
  47006. if (isNaN(this.rotation.y)) {
  47007. this.rotation.y = 0;
  47008. }
  47009. if (isNaN(this.rotation.z)) {
  47010. this.rotation.z = 0;
  47011. }
  47012. if (this.rotationQuaternion) {
  47013. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47014. }
  47015. };
  47016. /**
  47017. * Return the current target position of the camera. This value is expressed in local space.
  47018. */
  47019. TargetCamera.prototype.getTarget = function () {
  47020. return this._currentTarget;
  47021. };
  47022. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47023. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47024. };
  47025. TargetCamera.prototype._updatePosition = function () {
  47026. if (this.parent) {
  47027. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47028. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47029. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47030. return;
  47031. }
  47032. this.position.addInPlace(this.cameraDirection);
  47033. };
  47034. TargetCamera.prototype._checkInputs = function () {
  47035. var needToMove = this._decideIfNeedsToMove();
  47036. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47037. // Move
  47038. if (needToMove) {
  47039. this._updatePosition();
  47040. }
  47041. // Rotate
  47042. if (needToRotate) {
  47043. this.rotation.x += this.cameraRotation.x;
  47044. this.rotation.y += this.cameraRotation.y;
  47045. //rotate, if quaternion is set and rotation was used
  47046. if (this.rotationQuaternion) {
  47047. var len = this.rotation.lengthSquared();
  47048. if (len) {
  47049. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47050. }
  47051. }
  47052. if (!this.noRotationConstraint) {
  47053. var limit = (Math.PI / 2) * 0.95;
  47054. if (this.rotation.x > limit)
  47055. this.rotation.x = limit;
  47056. if (this.rotation.x < -limit)
  47057. this.rotation.x = -limit;
  47058. }
  47059. }
  47060. // Inertia
  47061. if (needToMove) {
  47062. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47063. this.cameraDirection.x = 0;
  47064. }
  47065. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47066. this.cameraDirection.y = 0;
  47067. }
  47068. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47069. this.cameraDirection.z = 0;
  47070. }
  47071. this.cameraDirection.scaleInPlace(this.inertia);
  47072. }
  47073. if (needToRotate) {
  47074. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47075. this.cameraRotation.x = 0;
  47076. }
  47077. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47078. this.cameraRotation.y = 0;
  47079. }
  47080. this.cameraRotation.scaleInPlace(this.inertia);
  47081. }
  47082. _super.prototype._checkInputs.call(this);
  47083. };
  47084. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47085. if (this.rotationQuaternion) {
  47086. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47087. }
  47088. else {
  47089. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47090. }
  47091. //update the up vector!
  47092. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47093. };
  47094. TargetCamera.prototype._getViewMatrix = function () {
  47095. if (this.lockedTarget) {
  47096. this.setTarget(this._getLockedTargetPosition());
  47097. }
  47098. // Compute
  47099. this._updateCameraRotationMatrix();
  47100. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47101. // Computing target and final matrix
  47102. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47103. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47104. return this._viewMatrix;
  47105. };
  47106. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47107. if (this.parent) {
  47108. var parentWorldMatrix = this.parent.getWorldMatrix();
  47109. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47110. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47111. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47112. this._markSyncedWithParent();
  47113. }
  47114. else {
  47115. this._globalPosition.copyFrom(this.position);
  47116. this._globalCurrentTarget.copyFrom(target);
  47117. this._globalCurrentUpVector.copyFrom(up);
  47118. }
  47119. if (this.getScene().useRightHandedSystem) {
  47120. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47121. }
  47122. else {
  47123. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47124. }
  47125. };
  47126. /**
  47127. * @override
  47128. * Override Camera.createRigCamera
  47129. */
  47130. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47131. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47132. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47133. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47134. if (!this.rotationQuaternion) {
  47135. this.rotationQuaternion = new BABYLON.Quaternion();
  47136. }
  47137. rigCamera._cameraRigParams = {};
  47138. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47139. }
  47140. return rigCamera;
  47141. }
  47142. return null;
  47143. };
  47144. /**
  47145. * @override
  47146. * Override Camera._updateRigCameras
  47147. */
  47148. TargetCamera.prototype._updateRigCameras = function () {
  47149. var camLeft = this._rigCameras[0];
  47150. var camRight = this._rigCameras[1];
  47151. switch (this.cameraRigMode) {
  47152. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47153. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47155. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47156. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47157. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47158. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47159. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47160. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47161. camLeft.setTarget(this.getTarget());
  47162. camRight.setTarget(this.getTarget());
  47163. break;
  47164. case BABYLON.Camera.RIG_MODE_VR:
  47165. if (camLeft.rotationQuaternion) {
  47166. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47167. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47168. }
  47169. else {
  47170. camLeft.rotation.copyFrom(this.rotation);
  47171. camRight.rotation.copyFrom(this.rotation);
  47172. }
  47173. camLeft.position.copyFrom(this.position);
  47174. camRight.position.copyFrom(this.position);
  47175. break;
  47176. }
  47177. _super.prototype._updateRigCameras.call(this);
  47178. };
  47179. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47180. if (!this._rigCamTransformMatrix) {
  47181. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47182. }
  47183. var target = this.getTarget();
  47184. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47185. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47186. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47187. };
  47188. TargetCamera.prototype.getClassName = function () {
  47189. return "TargetCamera";
  47190. };
  47191. __decorate([
  47192. BABYLON.serializeAsVector3()
  47193. ], TargetCamera.prototype, "rotation", void 0);
  47194. __decorate([
  47195. BABYLON.serialize()
  47196. ], TargetCamera.prototype, "speed", void 0);
  47197. __decorate([
  47198. BABYLON.serializeAsMeshReference("lockedTargetId")
  47199. ], TargetCamera.prototype, "lockedTarget", void 0);
  47200. return TargetCamera;
  47201. }(BABYLON.Camera));
  47202. BABYLON.TargetCamera = TargetCamera;
  47203. })(BABYLON || (BABYLON = {}));
  47204. //# sourceMappingURL=babylon.targetCamera.js.map
  47205. var BABYLON;
  47206. (function (BABYLON) {
  47207. var FreeCameraMouseInput = /** @class */ (function () {
  47208. function FreeCameraMouseInput(touchEnabled) {
  47209. if (touchEnabled === void 0) { touchEnabled = true; }
  47210. this.touchEnabled = touchEnabled;
  47211. this.buttons = [0, 1, 2];
  47212. this.angularSensibility = 2000.0;
  47213. this.previousPosition = null;
  47214. }
  47215. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47216. var _this = this;
  47217. var engine = this.camera.getEngine();
  47218. if (!this._pointerInput) {
  47219. this._pointerInput = function (p, s) {
  47220. var evt = p.event;
  47221. if (engine.isInVRExclusivePointerMode) {
  47222. return;
  47223. }
  47224. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47225. return;
  47226. }
  47227. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47228. return;
  47229. }
  47230. var srcElement = (evt.srcElement || evt.target);
  47231. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47232. try {
  47233. srcElement.setPointerCapture(evt.pointerId);
  47234. }
  47235. catch (e) {
  47236. //Nothing to do with the error. Execution will continue.
  47237. }
  47238. _this.previousPosition = {
  47239. x: evt.clientX,
  47240. y: evt.clientY
  47241. };
  47242. if (!noPreventDefault) {
  47243. evt.preventDefault();
  47244. element.focus();
  47245. }
  47246. }
  47247. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47248. try {
  47249. srcElement.releasePointerCapture(evt.pointerId);
  47250. }
  47251. catch (e) {
  47252. //Nothing to do with the error.
  47253. }
  47254. _this.previousPosition = null;
  47255. if (!noPreventDefault) {
  47256. evt.preventDefault();
  47257. }
  47258. }
  47259. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47260. if (!_this.previousPosition || engine.isPointerLock) {
  47261. return;
  47262. }
  47263. var offsetX = evt.clientX - _this.previousPosition.x;
  47264. if (_this.camera.getScene().useRightHandedSystem)
  47265. offsetX *= -1;
  47266. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47267. offsetX *= -1;
  47268. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47269. var offsetY = evt.clientY - _this.previousPosition.y;
  47270. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47271. _this.previousPosition = {
  47272. x: evt.clientX,
  47273. y: evt.clientY
  47274. };
  47275. if (!noPreventDefault) {
  47276. evt.preventDefault();
  47277. }
  47278. }
  47279. };
  47280. }
  47281. this._onMouseMove = function (evt) {
  47282. if (!engine.isPointerLock) {
  47283. return;
  47284. }
  47285. if (engine.isInVRExclusivePointerMode) {
  47286. return;
  47287. }
  47288. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47289. if (_this.camera.getScene().useRightHandedSystem)
  47290. offsetX *= -1;
  47291. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47292. offsetX *= -1;
  47293. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47294. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47295. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47296. _this.previousPosition = null;
  47297. if (!noPreventDefault) {
  47298. evt.preventDefault();
  47299. }
  47300. };
  47301. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47302. element.addEventListener("mousemove", this._onMouseMove, false);
  47303. };
  47304. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47305. if (this._observer && element) {
  47306. this.camera.getScene().onPointerObservable.remove(this._observer);
  47307. if (this._onMouseMove) {
  47308. element.removeEventListener("mousemove", this._onMouseMove);
  47309. }
  47310. this._observer = null;
  47311. this._onMouseMove = null;
  47312. this.previousPosition = null;
  47313. }
  47314. };
  47315. FreeCameraMouseInput.prototype.getClassName = function () {
  47316. return "FreeCameraMouseInput";
  47317. };
  47318. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47319. return "mouse";
  47320. };
  47321. __decorate([
  47322. BABYLON.serialize()
  47323. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47324. __decorate([
  47325. BABYLON.serialize()
  47326. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47327. return FreeCameraMouseInput;
  47328. }());
  47329. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47330. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47331. })(BABYLON || (BABYLON = {}));
  47332. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47333. var BABYLON;
  47334. (function (BABYLON) {
  47335. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47336. function FreeCameraKeyboardMoveInput() {
  47337. this._keys = new Array();
  47338. this.keysUp = [38];
  47339. this.keysDown = [40];
  47340. this.keysLeft = [37];
  47341. this.keysRight = [39];
  47342. }
  47343. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47344. var _this = this;
  47345. if (this._onCanvasBlurObserver) {
  47346. return;
  47347. }
  47348. this._scene = this.camera.getScene();
  47349. this._engine = this._scene.getEngine();
  47350. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47351. _this._keys = [];
  47352. });
  47353. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47354. var evt = info.event;
  47355. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47356. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47357. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47358. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47359. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47360. var index = _this._keys.indexOf(evt.keyCode);
  47361. if (index === -1) {
  47362. _this._keys.push(evt.keyCode);
  47363. }
  47364. if (!noPreventDefault) {
  47365. evt.preventDefault();
  47366. }
  47367. }
  47368. }
  47369. else {
  47370. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47371. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47372. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47373. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47374. var index = _this._keys.indexOf(evt.keyCode);
  47375. if (index >= 0) {
  47376. _this._keys.splice(index, 1);
  47377. }
  47378. if (!noPreventDefault) {
  47379. evt.preventDefault();
  47380. }
  47381. }
  47382. }
  47383. });
  47384. };
  47385. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47386. if (this._scene) {
  47387. if (this._onKeyboardObserver) {
  47388. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47389. }
  47390. if (this._onCanvasBlurObserver) {
  47391. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47392. }
  47393. this._onKeyboardObserver = null;
  47394. this._onCanvasBlurObserver = null;
  47395. }
  47396. this._keys = [];
  47397. };
  47398. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47399. if (this._onKeyboardObserver) {
  47400. var camera = this.camera;
  47401. // Keyboard
  47402. for (var index = 0; index < this._keys.length; index++) {
  47403. var keyCode = this._keys[index];
  47404. var speed = camera._computeLocalCameraSpeed();
  47405. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47406. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47407. }
  47408. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47409. camera._localDirection.copyFromFloats(0, 0, speed);
  47410. }
  47411. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47412. camera._localDirection.copyFromFloats(speed, 0, 0);
  47413. }
  47414. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47415. camera._localDirection.copyFromFloats(0, 0, -speed);
  47416. }
  47417. if (camera.getScene().useRightHandedSystem) {
  47418. camera._localDirection.z *= -1;
  47419. }
  47420. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47421. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47422. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47423. }
  47424. }
  47425. };
  47426. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47427. return "FreeCameraKeyboardMoveInput";
  47428. };
  47429. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47430. this._keys = [];
  47431. };
  47432. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47433. return "keyboard";
  47434. };
  47435. __decorate([
  47436. BABYLON.serialize()
  47437. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47438. __decorate([
  47439. BABYLON.serialize()
  47440. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47441. __decorate([
  47442. BABYLON.serialize()
  47443. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47444. __decorate([
  47445. BABYLON.serialize()
  47446. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47447. return FreeCameraKeyboardMoveInput;
  47448. }());
  47449. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47450. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47451. })(BABYLON || (BABYLON = {}));
  47452. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47453. var BABYLON;
  47454. (function (BABYLON) {
  47455. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47456. __extends(FreeCameraInputsManager, _super);
  47457. function FreeCameraInputsManager(camera) {
  47458. return _super.call(this, camera) || this;
  47459. }
  47460. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47461. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47462. return this;
  47463. };
  47464. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47465. if (touchEnabled === void 0) { touchEnabled = true; }
  47466. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47467. return this;
  47468. };
  47469. FreeCameraInputsManager.prototype.addGamepad = function () {
  47470. this.add(new BABYLON.FreeCameraGamepadInput());
  47471. return this;
  47472. };
  47473. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47474. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47475. return this;
  47476. };
  47477. FreeCameraInputsManager.prototype.addTouch = function () {
  47478. this.add(new BABYLON.FreeCameraTouchInput());
  47479. return this;
  47480. };
  47481. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47482. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47483. return this;
  47484. };
  47485. return FreeCameraInputsManager;
  47486. }(BABYLON.CameraInputsManager));
  47487. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47488. })(BABYLON || (BABYLON = {}));
  47489. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47490. var BABYLON;
  47491. (function (BABYLON) {
  47492. var FreeCamera = /** @class */ (function (_super) {
  47493. __extends(FreeCamera, _super);
  47494. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47495. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47496. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47497. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47498. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47499. _this.checkCollisions = false;
  47500. _this.applyGravity = false;
  47501. _this._needMoveForGravity = false;
  47502. _this._oldPosition = BABYLON.Vector3.Zero();
  47503. _this._diffPosition = BABYLON.Vector3.Zero();
  47504. _this._newPosition = BABYLON.Vector3.Zero();
  47505. // Collisions
  47506. _this._collisionMask = -1;
  47507. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47508. if (collidedMesh === void 0) { collidedMesh = null; }
  47509. //TODO move this to the collision coordinator!
  47510. if (_this.getScene().workerCollisions)
  47511. newPosition.multiplyInPlace(_this._collider._radius);
  47512. var updatePosition = function (newPos) {
  47513. _this._newPosition.copyFrom(newPos);
  47514. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47515. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47516. _this.position.addInPlace(_this._diffPosition);
  47517. if (_this.onCollide && collidedMesh) {
  47518. _this.onCollide(collidedMesh);
  47519. }
  47520. }
  47521. };
  47522. updatePosition(newPosition);
  47523. };
  47524. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47525. _this.inputs.addKeyboard().addMouse();
  47526. return _this;
  47527. }
  47528. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47529. //-- begin properties for backward compatibility for inputs
  47530. /**
  47531. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47532. * Higher values reduce sensitivity.
  47533. */
  47534. get: function () {
  47535. var mouse = this.inputs.attached["mouse"];
  47536. if (mouse)
  47537. return mouse.angularSensibility;
  47538. return 0;
  47539. },
  47540. /**
  47541. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47542. * Higher values reduce sensitivity.
  47543. */
  47544. set: function (value) {
  47545. var mouse = this.inputs.attached["mouse"];
  47546. if (mouse)
  47547. mouse.angularSensibility = value;
  47548. },
  47549. enumerable: true,
  47550. configurable: true
  47551. });
  47552. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47553. get: function () {
  47554. var keyboard = this.inputs.attached["keyboard"];
  47555. if (keyboard)
  47556. return keyboard.keysUp;
  47557. return [];
  47558. },
  47559. set: function (value) {
  47560. var keyboard = this.inputs.attached["keyboard"];
  47561. if (keyboard)
  47562. keyboard.keysUp = value;
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47568. get: function () {
  47569. var keyboard = this.inputs.attached["keyboard"];
  47570. if (keyboard)
  47571. return keyboard.keysDown;
  47572. return [];
  47573. },
  47574. set: function (value) {
  47575. var keyboard = this.inputs.attached["keyboard"];
  47576. if (keyboard)
  47577. keyboard.keysDown = value;
  47578. },
  47579. enumerable: true,
  47580. configurable: true
  47581. });
  47582. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47583. get: function () {
  47584. var keyboard = this.inputs.attached["keyboard"];
  47585. if (keyboard)
  47586. return keyboard.keysLeft;
  47587. return [];
  47588. },
  47589. set: function (value) {
  47590. var keyboard = this.inputs.attached["keyboard"];
  47591. if (keyboard)
  47592. keyboard.keysLeft = value;
  47593. },
  47594. enumerable: true,
  47595. configurable: true
  47596. });
  47597. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47598. get: function () {
  47599. var keyboard = this.inputs.attached["keyboard"];
  47600. if (keyboard)
  47601. return keyboard.keysRight;
  47602. return [];
  47603. },
  47604. set: function (value) {
  47605. var keyboard = this.inputs.attached["keyboard"];
  47606. if (keyboard)
  47607. keyboard.keysRight = value;
  47608. },
  47609. enumerable: true,
  47610. configurable: true
  47611. });
  47612. // Controls
  47613. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47614. this.inputs.attachElement(element, noPreventDefault);
  47615. };
  47616. FreeCamera.prototype.detachControl = function (element) {
  47617. this.inputs.detachElement(element);
  47618. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47619. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47620. };
  47621. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47622. get: function () {
  47623. return this._collisionMask;
  47624. },
  47625. set: function (mask) {
  47626. this._collisionMask = !isNaN(mask) ? mask : -1;
  47627. },
  47628. enumerable: true,
  47629. configurable: true
  47630. });
  47631. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47632. var globalPosition;
  47633. if (this.parent) {
  47634. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47635. }
  47636. else {
  47637. globalPosition = this.position;
  47638. }
  47639. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47640. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47641. if (!this._collider) {
  47642. this._collider = new BABYLON.Collider();
  47643. }
  47644. this._collider._radius = this.ellipsoid;
  47645. this._collider.collisionMask = this._collisionMask;
  47646. //no need for clone, as long as gravity is not on.
  47647. var actualDisplacement = displacement;
  47648. //add gravity to the direction to prevent the dual-collision checking
  47649. if (this.applyGravity) {
  47650. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47651. actualDisplacement = displacement.add(this.getScene().gravity);
  47652. }
  47653. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47654. };
  47655. FreeCamera.prototype._checkInputs = function () {
  47656. if (!this._localDirection) {
  47657. this._localDirection = BABYLON.Vector3.Zero();
  47658. this._transformedDirection = BABYLON.Vector3.Zero();
  47659. }
  47660. this.inputs.checkInputs();
  47661. _super.prototype._checkInputs.call(this);
  47662. };
  47663. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47664. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47665. };
  47666. FreeCamera.prototype._updatePosition = function () {
  47667. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47668. this._collideWithWorld(this.cameraDirection);
  47669. }
  47670. else {
  47671. _super.prototype._updatePosition.call(this);
  47672. }
  47673. };
  47674. FreeCamera.prototype.dispose = function () {
  47675. this.inputs.clear();
  47676. _super.prototype.dispose.call(this);
  47677. };
  47678. FreeCamera.prototype.getClassName = function () {
  47679. return "FreeCamera";
  47680. };
  47681. __decorate([
  47682. BABYLON.serializeAsVector3()
  47683. ], FreeCamera.prototype, "ellipsoid", void 0);
  47684. __decorate([
  47685. BABYLON.serializeAsVector3()
  47686. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47687. __decorate([
  47688. BABYLON.serialize()
  47689. ], FreeCamera.prototype, "checkCollisions", void 0);
  47690. __decorate([
  47691. BABYLON.serialize()
  47692. ], FreeCamera.prototype, "applyGravity", void 0);
  47693. return FreeCamera;
  47694. }(BABYLON.TargetCamera));
  47695. BABYLON.FreeCamera = FreeCamera;
  47696. })(BABYLON || (BABYLON = {}));
  47697. //# sourceMappingURL=babylon.freeCamera.js.map
  47698. var BABYLON;
  47699. (function (BABYLON) {
  47700. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47701. function ArcRotateCameraKeyboardMoveInput() {
  47702. this._keys = new Array();
  47703. this.keysUp = [38];
  47704. this.keysDown = [40];
  47705. this.keysLeft = [37];
  47706. this.keysRight = [39];
  47707. this.keysReset = [220];
  47708. this.panningSensibility = 50.0;
  47709. this.zoomingSensibility = 25.0;
  47710. this.useAltToZoom = true;
  47711. }
  47712. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47713. var _this = this;
  47714. if (this._onCanvasBlurObserver) {
  47715. return;
  47716. }
  47717. this._scene = this.camera.getScene();
  47718. this._engine = this._scene.getEngine();
  47719. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47720. _this._keys = [];
  47721. });
  47722. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47723. var evt = info.event;
  47724. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47725. _this._ctrlPressed = evt.ctrlKey;
  47726. _this._altPressed = evt.altKey;
  47727. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47728. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47729. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47730. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47731. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47732. var index = _this._keys.indexOf(evt.keyCode);
  47733. if (index === -1) {
  47734. _this._keys.push(evt.keyCode);
  47735. }
  47736. if (evt.preventDefault) {
  47737. if (!noPreventDefault) {
  47738. evt.preventDefault();
  47739. }
  47740. }
  47741. }
  47742. }
  47743. else {
  47744. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47745. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47746. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47747. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47748. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47749. var index = _this._keys.indexOf(evt.keyCode);
  47750. if (index >= 0) {
  47751. _this._keys.splice(index, 1);
  47752. }
  47753. if (evt.preventDefault) {
  47754. if (!noPreventDefault) {
  47755. evt.preventDefault();
  47756. }
  47757. }
  47758. }
  47759. }
  47760. });
  47761. };
  47762. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47763. if (this._scene) {
  47764. if (this._onKeyboardObserver) {
  47765. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47766. }
  47767. if (this._onCanvasBlurObserver) {
  47768. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47769. }
  47770. this._onKeyboardObserver = null;
  47771. this._onCanvasBlurObserver = null;
  47772. }
  47773. this._keys = [];
  47774. };
  47775. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47776. if (this._onKeyboardObserver) {
  47777. var camera = this.camera;
  47778. for (var index = 0; index < this._keys.length; index++) {
  47779. var keyCode = this._keys[index];
  47780. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47781. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47782. camera.inertialPanningX -= 1 / this.panningSensibility;
  47783. }
  47784. else {
  47785. camera.inertialAlphaOffset -= 0.01;
  47786. }
  47787. }
  47788. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47789. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47790. camera.inertialPanningY += 1 / this.panningSensibility;
  47791. }
  47792. else if (this._altPressed && this.useAltToZoom) {
  47793. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47794. }
  47795. else {
  47796. camera.inertialBetaOffset -= 0.01;
  47797. }
  47798. }
  47799. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47800. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47801. camera.inertialPanningX += 1 / this.panningSensibility;
  47802. }
  47803. else {
  47804. camera.inertialAlphaOffset += 0.01;
  47805. }
  47806. }
  47807. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47808. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47809. camera.inertialPanningY -= 1 / this.panningSensibility;
  47810. }
  47811. else if (this._altPressed && this.useAltToZoom) {
  47812. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47813. }
  47814. else {
  47815. camera.inertialBetaOffset += 0.01;
  47816. }
  47817. }
  47818. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47819. camera.restoreState();
  47820. }
  47821. }
  47822. }
  47823. };
  47824. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47825. return "ArcRotateCameraKeyboardMoveInput";
  47826. };
  47827. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47828. return "keyboard";
  47829. };
  47830. __decorate([
  47831. BABYLON.serialize()
  47832. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47833. __decorate([
  47834. BABYLON.serialize()
  47835. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47836. __decorate([
  47837. BABYLON.serialize()
  47838. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47839. __decorate([
  47840. BABYLON.serialize()
  47841. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47842. __decorate([
  47843. BABYLON.serialize()
  47844. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47845. __decorate([
  47846. BABYLON.serialize()
  47847. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47848. __decorate([
  47849. BABYLON.serialize()
  47850. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47851. __decorate([
  47852. BABYLON.serialize()
  47853. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47854. return ArcRotateCameraKeyboardMoveInput;
  47855. }());
  47856. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47857. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47858. })(BABYLON || (BABYLON = {}));
  47859. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47860. var BABYLON;
  47861. (function (BABYLON) {
  47862. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47863. function ArcRotateCameraMouseWheelInput() {
  47864. this.wheelPrecision = 3.0;
  47865. /**
  47866. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47867. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47868. */
  47869. this.wheelDeltaPercentage = 0;
  47870. }
  47871. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47872. var _this = this;
  47873. this._wheel = function (p, s) {
  47874. //sanity check - this should be a PointerWheel event.
  47875. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47876. return;
  47877. var event = p.event;
  47878. var delta = 0;
  47879. if (event.wheelDelta) {
  47880. if (_this.wheelDeltaPercentage) {
  47881. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47882. if (event.wheelDelta > 0) {
  47883. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47884. }
  47885. else {
  47886. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47887. }
  47888. }
  47889. else {
  47890. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47891. }
  47892. }
  47893. else if (event.detail) {
  47894. delta = -event.detail / _this.wheelPrecision;
  47895. }
  47896. if (delta)
  47897. _this.camera.inertialRadiusOffset += delta;
  47898. if (event.preventDefault) {
  47899. if (!noPreventDefault) {
  47900. event.preventDefault();
  47901. }
  47902. }
  47903. };
  47904. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47905. };
  47906. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47907. if (this._observer && element) {
  47908. this.camera.getScene().onPointerObservable.remove(this._observer);
  47909. this._observer = null;
  47910. this._wheel = null;
  47911. }
  47912. };
  47913. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47914. return "ArcRotateCameraMouseWheelInput";
  47915. };
  47916. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47917. return "mousewheel";
  47918. };
  47919. __decorate([
  47920. BABYLON.serialize()
  47921. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47922. __decorate([
  47923. BABYLON.serialize()
  47924. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47925. return ArcRotateCameraMouseWheelInput;
  47926. }());
  47927. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47928. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47929. })(BABYLON || (BABYLON = {}));
  47930. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47931. var BABYLON;
  47932. (function (BABYLON) {
  47933. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47934. function ArcRotateCameraPointersInput() {
  47935. this.buttons = [0, 1, 2];
  47936. this.angularSensibilityX = 1000.0;
  47937. this.angularSensibilityY = 1000.0;
  47938. this.pinchPrecision = 12.0;
  47939. /**
  47940. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47941. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47942. */
  47943. this.pinchDeltaPercentage = 0;
  47944. this.panningSensibility = 1000.0;
  47945. this.multiTouchPanning = true;
  47946. this.multiTouchPanAndZoom = true;
  47947. this._isPanClick = false;
  47948. this.pinchInwards = true;
  47949. }
  47950. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47951. var _this = this;
  47952. var engine = this.camera.getEngine();
  47953. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47954. var pointA = null;
  47955. var pointB = null;
  47956. var previousPinchSquaredDistance = 0;
  47957. var initialDistance = 0;
  47958. var twoFingerActivityCount = 0;
  47959. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47960. this._pointerInput = function (p, s) {
  47961. var evt = p.event;
  47962. var isTouch = p.event.pointerType === "touch";
  47963. if (engine.isInVRExclusivePointerMode) {
  47964. return;
  47965. }
  47966. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47967. return;
  47968. }
  47969. var srcElement = (evt.srcElement || evt.target);
  47970. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47971. try {
  47972. srcElement.setPointerCapture(evt.pointerId);
  47973. }
  47974. catch (e) {
  47975. //Nothing to do with the error. Execution will continue.
  47976. }
  47977. // Manage panning with pan button click
  47978. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47979. // manage pointers
  47980. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47981. if (pointA === null) {
  47982. pointA = cacheSoloPointer;
  47983. }
  47984. else if (pointB === null) {
  47985. pointB = cacheSoloPointer;
  47986. }
  47987. if (!noPreventDefault) {
  47988. evt.preventDefault();
  47989. element.focus();
  47990. }
  47991. }
  47992. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47993. _this.camera.restoreState();
  47994. }
  47995. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47996. try {
  47997. srcElement.releasePointerCapture(evt.pointerId);
  47998. }
  47999. catch (e) {
  48000. //Nothing to do with the error.
  48001. }
  48002. cacheSoloPointer = null;
  48003. previousPinchSquaredDistance = 0;
  48004. previousMultiTouchPanPosition.isPaning = false;
  48005. previousMultiTouchPanPosition.isPinching = false;
  48006. twoFingerActivityCount = 0;
  48007. initialDistance = 0;
  48008. if (!isTouch) {
  48009. pointB = null; // Mouse and pen are mono pointer
  48010. }
  48011. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48012. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48013. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48014. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48015. if (engine._badOS) {
  48016. pointA = pointB = null;
  48017. }
  48018. else {
  48019. //only remove the impacted pointer in case of multitouch allowing on most
  48020. //platforms switching from rotate to zoom and pan seamlessly.
  48021. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48022. pointA = pointB;
  48023. pointB = null;
  48024. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48025. }
  48026. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48027. pointB = null;
  48028. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48029. }
  48030. else {
  48031. pointA = pointB = null;
  48032. }
  48033. }
  48034. if (!noPreventDefault) {
  48035. evt.preventDefault();
  48036. }
  48037. }
  48038. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48039. if (!noPreventDefault) {
  48040. evt.preventDefault();
  48041. }
  48042. // One button down
  48043. if (pointA && pointB === null && cacheSoloPointer) {
  48044. if (_this.panningSensibility !== 0 &&
  48045. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48046. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48047. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48048. }
  48049. else {
  48050. var offsetX = evt.clientX - cacheSoloPointer.x;
  48051. var offsetY = evt.clientY - cacheSoloPointer.y;
  48052. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48053. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48054. }
  48055. cacheSoloPointer.x = evt.clientX;
  48056. cacheSoloPointer.y = evt.clientY;
  48057. }
  48058. // Two buttons down: pinch/pan
  48059. else if (pointA && pointB) {
  48060. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48061. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48062. ed.x = evt.clientX;
  48063. ed.y = evt.clientY;
  48064. var direction = _this.pinchInwards ? 1 : -1;
  48065. var distX = pointA.x - pointB.x;
  48066. var distY = pointA.y - pointB.y;
  48067. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48068. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48069. if (previousPinchSquaredDistance === 0) {
  48070. initialDistance = pinchDistance;
  48071. previousPinchSquaredDistance = pinchSquaredDistance;
  48072. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48073. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48074. return;
  48075. }
  48076. if (_this.multiTouchPanAndZoom) {
  48077. if (_this.pinchDeltaPercentage) {
  48078. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48079. }
  48080. else {
  48081. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48082. (_this.pinchPrecision *
  48083. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48084. direction);
  48085. }
  48086. if (_this.panningSensibility !== 0) {
  48087. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48088. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48089. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48090. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48091. previousMultiTouchPanPosition.x = pointersCenterX;
  48092. previousMultiTouchPanPosition.y = pointersCenterY;
  48093. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48094. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48095. }
  48096. }
  48097. else {
  48098. twoFingerActivityCount++;
  48099. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48100. if (_this.pinchDeltaPercentage) {
  48101. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48102. }
  48103. else {
  48104. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48105. (_this.pinchPrecision *
  48106. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48107. direction);
  48108. }
  48109. previousMultiTouchPanPosition.isPaning = false;
  48110. previousMultiTouchPanPosition.isPinching = true;
  48111. }
  48112. else {
  48113. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48114. if (!previousMultiTouchPanPosition.isPaning) {
  48115. previousMultiTouchPanPosition.isPaning = true;
  48116. previousMultiTouchPanPosition.isPinching = false;
  48117. previousMultiTouchPanPosition.x = ed.x;
  48118. previousMultiTouchPanPosition.y = ed.y;
  48119. return;
  48120. }
  48121. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48122. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48123. }
  48124. }
  48125. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48126. previousMultiTouchPanPosition.x = ed.x;
  48127. previousMultiTouchPanPosition.y = ed.y;
  48128. }
  48129. }
  48130. previousPinchSquaredDistance = pinchSquaredDistance;
  48131. }
  48132. }
  48133. };
  48134. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48135. this._onContextMenu = function (evt) {
  48136. evt.preventDefault();
  48137. };
  48138. if (!this.camera._useCtrlForPanning) {
  48139. element.addEventListener("contextmenu", this._onContextMenu, false);
  48140. }
  48141. this._onLostFocus = function () {
  48142. //this._keys = [];
  48143. pointA = pointB = null;
  48144. previousPinchSquaredDistance = 0;
  48145. previousMultiTouchPanPosition.isPaning = false;
  48146. previousMultiTouchPanPosition.isPinching = false;
  48147. twoFingerActivityCount = 0;
  48148. cacheSoloPointer = null;
  48149. initialDistance = 0;
  48150. };
  48151. this._onMouseMove = function (evt) {
  48152. if (!engine.isPointerLock) {
  48153. return;
  48154. }
  48155. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48156. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48157. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48158. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48159. if (!noPreventDefault) {
  48160. evt.preventDefault();
  48161. }
  48162. };
  48163. this._onGestureStart = function (e) {
  48164. if (window.MSGesture === undefined) {
  48165. return;
  48166. }
  48167. if (!_this._MSGestureHandler) {
  48168. _this._MSGestureHandler = new MSGesture();
  48169. _this._MSGestureHandler.target = element;
  48170. }
  48171. _this._MSGestureHandler.addPointer(e.pointerId);
  48172. };
  48173. this._onGesture = function (e) {
  48174. _this.camera.radius *= e.scale;
  48175. if (e.preventDefault) {
  48176. if (!noPreventDefault) {
  48177. e.stopPropagation();
  48178. e.preventDefault();
  48179. }
  48180. }
  48181. };
  48182. element.addEventListener("mousemove", this._onMouseMove, false);
  48183. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48184. element.addEventListener("MSGestureChange", this._onGesture, false);
  48185. BABYLON.Tools.RegisterTopRootEvents([
  48186. { name: "blur", handler: this._onLostFocus }
  48187. ]);
  48188. };
  48189. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48190. if (this._onLostFocus) {
  48191. BABYLON.Tools.UnregisterTopRootEvents([
  48192. { name: "blur", handler: this._onLostFocus }
  48193. ]);
  48194. }
  48195. if (element && this._observer) {
  48196. this.camera.getScene().onPointerObservable.remove(this._observer);
  48197. this._observer = null;
  48198. if (this._onContextMenu) {
  48199. element.removeEventListener("contextmenu", this._onContextMenu);
  48200. }
  48201. if (this._onMouseMove) {
  48202. element.removeEventListener("mousemove", this._onMouseMove);
  48203. }
  48204. if (this._onGestureStart) {
  48205. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48206. }
  48207. if (this._onGesture) {
  48208. element.removeEventListener("MSGestureChange", this._onGesture);
  48209. }
  48210. this._isPanClick = false;
  48211. this.pinchInwards = true;
  48212. this._onMouseMove = null;
  48213. this._onGestureStart = null;
  48214. this._onGesture = null;
  48215. this._MSGestureHandler = null;
  48216. this._onLostFocus = null;
  48217. this._onContextMenu = null;
  48218. }
  48219. };
  48220. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48221. return "ArcRotateCameraPointersInput";
  48222. };
  48223. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48224. return "pointers";
  48225. };
  48226. __decorate([
  48227. BABYLON.serialize()
  48228. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48229. __decorate([
  48230. BABYLON.serialize()
  48231. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48232. __decorate([
  48233. BABYLON.serialize()
  48234. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48235. __decorate([
  48236. BABYLON.serialize()
  48237. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48238. __decorate([
  48239. BABYLON.serialize()
  48240. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48241. __decorate([
  48242. BABYLON.serialize()
  48243. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48244. __decorate([
  48245. BABYLON.serialize()
  48246. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48247. __decorate([
  48248. BABYLON.serialize()
  48249. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48250. return ArcRotateCameraPointersInput;
  48251. }());
  48252. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48253. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48254. })(BABYLON || (BABYLON = {}));
  48255. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48256. var BABYLON;
  48257. (function (BABYLON) {
  48258. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48259. __extends(ArcRotateCameraInputsManager, _super);
  48260. function ArcRotateCameraInputsManager(camera) {
  48261. return _super.call(this, camera) || this;
  48262. }
  48263. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48264. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48265. return this;
  48266. };
  48267. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48268. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48269. return this;
  48270. };
  48271. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48272. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48273. return this;
  48274. };
  48275. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48276. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48277. return this;
  48278. };
  48279. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48280. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48281. return this;
  48282. };
  48283. return ArcRotateCameraInputsManager;
  48284. }(BABYLON.CameraInputsManager));
  48285. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48286. })(BABYLON || (BABYLON = {}));
  48287. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48288. var BABYLON;
  48289. (function (BABYLON) {
  48290. var ArcRotateCamera = /** @class */ (function (_super) {
  48291. __extends(ArcRotateCamera, _super);
  48292. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48293. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48294. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48295. _this.inertialAlphaOffset = 0;
  48296. _this.inertialBetaOffset = 0;
  48297. _this.inertialRadiusOffset = 0;
  48298. _this.lowerAlphaLimit = null;
  48299. _this.upperAlphaLimit = null;
  48300. _this.lowerBetaLimit = 0.01;
  48301. _this.upperBetaLimit = Math.PI;
  48302. _this.lowerRadiusLimit = null;
  48303. _this.upperRadiusLimit = null;
  48304. _this.inertialPanningX = 0;
  48305. _this.inertialPanningY = 0;
  48306. _this.pinchToPanMaxDistance = 20;
  48307. _this.panningDistanceLimit = null;
  48308. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48309. _this.panningInertia = 0.9;
  48310. //-- end properties for backward compatibility for inputs
  48311. _this.zoomOnFactor = 1;
  48312. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48313. _this.allowUpsideDown = true;
  48314. _this._viewMatrix = new BABYLON.Matrix();
  48315. // Panning
  48316. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48317. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48318. _this.checkCollisions = false;
  48319. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48320. _this._previousPosition = BABYLON.Vector3.Zero();
  48321. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48322. _this._newPosition = BABYLON.Vector3.Zero();
  48323. _this._computationVector = BABYLON.Vector3.Zero();
  48324. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48325. if (collidedMesh === void 0) { collidedMesh = null; }
  48326. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48327. newPosition.multiplyInPlace(_this._collider._radius);
  48328. }
  48329. if (!collidedMesh) {
  48330. _this._previousPosition.copyFrom(_this.position);
  48331. }
  48332. else {
  48333. _this.setPosition(newPosition);
  48334. if (_this.onCollide) {
  48335. _this.onCollide(collidedMesh);
  48336. }
  48337. }
  48338. // Recompute because of constraints
  48339. var cosa = Math.cos(_this.alpha);
  48340. var sina = Math.sin(_this.alpha);
  48341. var cosb = Math.cos(_this.beta);
  48342. var sinb = Math.sin(_this.beta);
  48343. if (sinb === 0) {
  48344. sinb = 0.0001;
  48345. }
  48346. var target = _this._getTargetPosition();
  48347. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48348. target.addToRef(_this._computationVector, _this._newPosition);
  48349. _this.position.copyFrom(_this._newPosition);
  48350. var up = _this.upVector;
  48351. if (_this.allowUpsideDown && _this.beta < 0) {
  48352. up = up.clone();
  48353. up = up.negate();
  48354. }
  48355. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48356. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48357. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48358. _this._collisionTriggered = false;
  48359. };
  48360. _this._target = BABYLON.Vector3.Zero();
  48361. if (target) {
  48362. _this.setTarget(target);
  48363. }
  48364. _this.alpha = alpha;
  48365. _this.beta = beta;
  48366. _this.radius = radius;
  48367. _this.getViewMatrix();
  48368. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48369. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48370. return _this;
  48371. }
  48372. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48373. get: function () {
  48374. return this._target;
  48375. },
  48376. set: function (value) {
  48377. this.setTarget(value);
  48378. },
  48379. enumerable: true,
  48380. configurable: true
  48381. });
  48382. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48383. //-- begin properties for backward compatibility for inputs
  48384. get: function () {
  48385. var pointers = this.inputs.attached["pointers"];
  48386. if (pointers)
  48387. return pointers.angularSensibilityX;
  48388. return 0;
  48389. },
  48390. set: function (value) {
  48391. var pointers = this.inputs.attached["pointers"];
  48392. if (pointers) {
  48393. pointers.angularSensibilityX = value;
  48394. }
  48395. },
  48396. enumerable: true,
  48397. configurable: true
  48398. });
  48399. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48400. get: function () {
  48401. var pointers = this.inputs.attached["pointers"];
  48402. if (pointers)
  48403. return pointers.angularSensibilityY;
  48404. return 0;
  48405. },
  48406. set: function (value) {
  48407. var pointers = this.inputs.attached["pointers"];
  48408. if (pointers) {
  48409. pointers.angularSensibilityY = value;
  48410. }
  48411. },
  48412. enumerable: true,
  48413. configurable: true
  48414. });
  48415. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48416. get: function () {
  48417. var pointers = this.inputs.attached["pointers"];
  48418. if (pointers)
  48419. return pointers.pinchPrecision;
  48420. return 0;
  48421. },
  48422. set: function (value) {
  48423. var pointers = this.inputs.attached["pointers"];
  48424. if (pointers) {
  48425. pointers.pinchPrecision = value;
  48426. }
  48427. },
  48428. enumerable: true,
  48429. configurable: true
  48430. });
  48431. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48432. get: function () {
  48433. var pointers = this.inputs.attached["pointers"];
  48434. if (pointers)
  48435. return pointers.pinchDeltaPercentage;
  48436. return 0;
  48437. },
  48438. set: function (value) {
  48439. var pointers = this.inputs.attached["pointers"];
  48440. if (pointers) {
  48441. pointers.pinchDeltaPercentage = value;
  48442. }
  48443. },
  48444. enumerable: true,
  48445. configurable: true
  48446. });
  48447. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48448. get: function () {
  48449. var pointers = this.inputs.attached["pointers"];
  48450. if (pointers)
  48451. return pointers.panningSensibility;
  48452. return 0;
  48453. },
  48454. set: function (value) {
  48455. var pointers = this.inputs.attached["pointers"];
  48456. if (pointers) {
  48457. pointers.panningSensibility = value;
  48458. }
  48459. },
  48460. enumerable: true,
  48461. configurable: true
  48462. });
  48463. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48464. get: function () {
  48465. var keyboard = this.inputs.attached["keyboard"];
  48466. if (keyboard)
  48467. return keyboard.keysUp;
  48468. return [];
  48469. },
  48470. set: function (value) {
  48471. var keyboard = this.inputs.attached["keyboard"];
  48472. if (keyboard)
  48473. keyboard.keysUp = value;
  48474. },
  48475. enumerable: true,
  48476. configurable: true
  48477. });
  48478. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48479. get: function () {
  48480. var keyboard = this.inputs.attached["keyboard"];
  48481. if (keyboard)
  48482. return keyboard.keysDown;
  48483. return [];
  48484. },
  48485. set: function (value) {
  48486. var keyboard = this.inputs.attached["keyboard"];
  48487. if (keyboard)
  48488. keyboard.keysDown = value;
  48489. },
  48490. enumerable: true,
  48491. configurable: true
  48492. });
  48493. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48494. get: function () {
  48495. var keyboard = this.inputs.attached["keyboard"];
  48496. if (keyboard)
  48497. return keyboard.keysLeft;
  48498. return [];
  48499. },
  48500. set: function (value) {
  48501. var keyboard = this.inputs.attached["keyboard"];
  48502. if (keyboard)
  48503. keyboard.keysLeft = value;
  48504. },
  48505. enumerable: true,
  48506. configurable: true
  48507. });
  48508. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48509. get: function () {
  48510. var keyboard = this.inputs.attached["keyboard"];
  48511. if (keyboard)
  48512. return keyboard.keysRight;
  48513. return [];
  48514. },
  48515. set: function (value) {
  48516. var keyboard = this.inputs.attached["keyboard"];
  48517. if (keyboard)
  48518. keyboard.keysRight = value;
  48519. },
  48520. enumerable: true,
  48521. configurable: true
  48522. });
  48523. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48524. get: function () {
  48525. var mousewheel = this.inputs.attached["mousewheel"];
  48526. if (mousewheel)
  48527. return mousewheel.wheelPrecision;
  48528. return 0;
  48529. },
  48530. set: function (value) {
  48531. var mousewheel = this.inputs.attached["mousewheel"];
  48532. if (mousewheel)
  48533. mousewheel.wheelPrecision = value;
  48534. },
  48535. enumerable: true,
  48536. configurable: true
  48537. });
  48538. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48539. get: function () {
  48540. var mousewheel = this.inputs.attached["mousewheel"];
  48541. if (mousewheel)
  48542. return mousewheel.wheelDeltaPercentage;
  48543. return 0;
  48544. },
  48545. set: function (value) {
  48546. var mousewheel = this.inputs.attached["mousewheel"];
  48547. if (mousewheel)
  48548. mousewheel.wheelDeltaPercentage = value;
  48549. },
  48550. enumerable: true,
  48551. configurable: true
  48552. });
  48553. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48554. get: function () {
  48555. return this._bouncingBehavior;
  48556. },
  48557. enumerable: true,
  48558. configurable: true
  48559. });
  48560. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48561. get: function () {
  48562. return this._bouncingBehavior != null;
  48563. },
  48564. set: function (value) {
  48565. if (value === this.useBouncingBehavior) {
  48566. return;
  48567. }
  48568. if (value) {
  48569. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48570. this.addBehavior(this._bouncingBehavior);
  48571. }
  48572. else if (this._bouncingBehavior) {
  48573. this.removeBehavior(this._bouncingBehavior);
  48574. this._bouncingBehavior = null;
  48575. }
  48576. },
  48577. enumerable: true,
  48578. configurable: true
  48579. });
  48580. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48581. get: function () {
  48582. return this._framingBehavior;
  48583. },
  48584. enumerable: true,
  48585. configurable: true
  48586. });
  48587. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48588. get: function () {
  48589. return this._framingBehavior != null;
  48590. },
  48591. set: function (value) {
  48592. if (value === this.useFramingBehavior) {
  48593. return;
  48594. }
  48595. if (value) {
  48596. this._framingBehavior = new BABYLON.FramingBehavior();
  48597. this.addBehavior(this._framingBehavior);
  48598. }
  48599. else if (this._framingBehavior) {
  48600. this.removeBehavior(this._framingBehavior);
  48601. this._framingBehavior = null;
  48602. }
  48603. },
  48604. enumerable: true,
  48605. configurable: true
  48606. });
  48607. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48608. get: function () {
  48609. return this._autoRotationBehavior;
  48610. },
  48611. enumerable: true,
  48612. configurable: true
  48613. });
  48614. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48615. get: function () {
  48616. return this._autoRotationBehavior != null;
  48617. },
  48618. set: function (value) {
  48619. if (value === this.useAutoRotationBehavior) {
  48620. return;
  48621. }
  48622. if (value) {
  48623. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48624. this.addBehavior(this._autoRotationBehavior);
  48625. }
  48626. else if (this._autoRotationBehavior) {
  48627. this.removeBehavior(this._autoRotationBehavior);
  48628. this._autoRotationBehavior = null;
  48629. }
  48630. },
  48631. enumerable: true,
  48632. configurable: true
  48633. });
  48634. // Cache
  48635. ArcRotateCamera.prototype._initCache = function () {
  48636. _super.prototype._initCache.call(this);
  48637. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48638. this._cache.alpha = undefined;
  48639. this._cache.beta = undefined;
  48640. this._cache.radius = undefined;
  48641. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48642. };
  48643. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48644. if (!ignoreParentClass) {
  48645. _super.prototype._updateCache.call(this);
  48646. }
  48647. this._cache._target.copyFrom(this._getTargetPosition());
  48648. this._cache.alpha = this.alpha;
  48649. this._cache.beta = this.beta;
  48650. this._cache.radius = this.radius;
  48651. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48652. };
  48653. ArcRotateCamera.prototype._getTargetPosition = function () {
  48654. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48655. var pos = this._targetHost.getAbsolutePosition();
  48656. if (this._targetBoundingCenter) {
  48657. pos.addToRef(this._targetBoundingCenter, this._target);
  48658. }
  48659. else {
  48660. this._target.copyFrom(pos);
  48661. }
  48662. }
  48663. var lockedTargetPosition = this._getLockedTargetPosition();
  48664. if (lockedTargetPosition) {
  48665. return lockedTargetPosition;
  48666. }
  48667. return this._target;
  48668. };
  48669. ArcRotateCamera.prototype.storeState = function () {
  48670. this._storedAlpha = this.alpha;
  48671. this._storedBeta = this.beta;
  48672. this._storedRadius = this.radius;
  48673. this._storedTarget = this._getTargetPosition().clone();
  48674. return _super.prototype.storeState.call(this);
  48675. };
  48676. /**
  48677. * Restored camera state. You must call storeState() first
  48678. */
  48679. ArcRotateCamera.prototype._restoreStateValues = function () {
  48680. if (!_super.prototype._restoreStateValues.call(this)) {
  48681. return false;
  48682. }
  48683. this.alpha = this._storedAlpha;
  48684. this.beta = this._storedBeta;
  48685. this.radius = this._storedRadius;
  48686. this.setTarget(this._storedTarget.clone());
  48687. this.inertialAlphaOffset = 0;
  48688. this.inertialBetaOffset = 0;
  48689. this.inertialRadiusOffset = 0;
  48690. this.inertialPanningX = 0;
  48691. this.inertialPanningY = 0;
  48692. return true;
  48693. };
  48694. // Synchronized
  48695. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48696. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48697. return false;
  48698. return this._cache._target.equals(this._getTargetPosition())
  48699. && this._cache.alpha === this.alpha
  48700. && this._cache.beta === this.beta
  48701. && this._cache.radius === this.radius
  48702. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48703. };
  48704. // Methods
  48705. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48706. var _this = this;
  48707. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48708. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48709. this._useCtrlForPanning = useCtrlForPanning;
  48710. this._panningMouseButton = panningMouseButton;
  48711. this.inputs.attachElement(element, noPreventDefault);
  48712. this._reset = function () {
  48713. _this.inertialAlphaOffset = 0;
  48714. _this.inertialBetaOffset = 0;
  48715. _this.inertialRadiusOffset = 0;
  48716. _this.inertialPanningX = 0;
  48717. _this.inertialPanningY = 0;
  48718. };
  48719. };
  48720. ArcRotateCamera.prototype.detachControl = function (element) {
  48721. this.inputs.detachElement(element);
  48722. if (this._reset) {
  48723. this._reset();
  48724. }
  48725. };
  48726. ArcRotateCamera.prototype._checkInputs = function () {
  48727. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48728. if (this._collisionTriggered) {
  48729. return;
  48730. }
  48731. this.inputs.checkInputs();
  48732. // Inertia
  48733. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48734. var inertialAlphaOffset = this.inertialAlphaOffset;
  48735. if (this.beta <= 0)
  48736. inertialAlphaOffset *= -1;
  48737. if (this.getScene().useRightHandedSystem)
  48738. inertialAlphaOffset *= -1;
  48739. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48740. inertialAlphaOffset *= -1;
  48741. this.alpha += inertialAlphaOffset;
  48742. this.beta += this.inertialBetaOffset;
  48743. this.radius -= this.inertialRadiusOffset;
  48744. this.inertialAlphaOffset *= this.inertia;
  48745. this.inertialBetaOffset *= this.inertia;
  48746. this.inertialRadiusOffset *= this.inertia;
  48747. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48748. this.inertialAlphaOffset = 0;
  48749. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48750. this.inertialBetaOffset = 0;
  48751. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48752. this.inertialRadiusOffset = 0;
  48753. }
  48754. // Panning inertia
  48755. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48756. if (!this._localDirection) {
  48757. this._localDirection = BABYLON.Vector3.Zero();
  48758. this._transformedDirection = BABYLON.Vector3.Zero();
  48759. }
  48760. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48761. this._localDirection.multiplyInPlace(this.panningAxis);
  48762. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48763. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48764. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48765. if (!this.panningAxis.y) {
  48766. this._transformedDirection.y = 0;
  48767. }
  48768. if (!this._targetHost) {
  48769. if (this.panningDistanceLimit) {
  48770. this._transformedDirection.addInPlace(this._target);
  48771. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48772. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48773. this._target.copyFrom(this._transformedDirection);
  48774. }
  48775. }
  48776. else {
  48777. this._target.addInPlace(this._transformedDirection);
  48778. }
  48779. }
  48780. this.inertialPanningX *= this.panningInertia;
  48781. this.inertialPanningY *= this.panningInertia;
  48782. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48783. this.inertialPanningX = 0;
  48784. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48785. this.inertialPanningY = 0;
  48786. }
  48787. // Limits
  48788. this._checkLimits();
  48789. _super.prototype._checkInputs.call(this);
  48790. };
  48791. ArcRotateCamera.prototype._checkLimits = function () {
  48792. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48793. if (this.allowUpsideDown && this.beta > Math.PI) {
  48794. this.beta = this.beta - (2 * Math.PI);
  48795. }
  48796. }
  48797. else {
  48798. if (this.beta < this.lowerBetaLimit) {
  48799. this.beta = this.lowerBetaLimit;
  48800. }
  48801. }
  48802. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48803. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48804. this.beta = this.beta + (2 * Math.PI);
  48805. }
  48806. }
  48807. else {
  48808. if (this.beta > this.upperBetaLimit) {
  48809. this.beta = this.upperBetaLimit;
  48810. }
  48811. }
  48812. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48813. this.alpha = this.lowerAlphaLimit;
  48814. }
  48815. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48816. this.alpha = this.upperAlphaLimit;
  48817. }
  48818. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48819. this.radius = this.lowerRadiusLimit;
  48820. }
  48821. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48822. this.radius = this.upperRadiusLimit;
  48823. }
  48824. };
  48825. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48826. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48827. this.radius = this._computationVector.length();
  48828. if (this.radius === 0) {
  48829. this.radius = 0.0001; // Just to avoid division by zero
  48830. }
  48831. // Alpha
  48832. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48833. if (this._computationVector.z < 0) {
  48834. this.alpha = 2 * Math.PI - this.alpha;
  48835. }
  48836. // Beta
  48837. this.beta = Math.acos(this._computationVector.y / this.radius);
  48838. this._checkLimits();
  48839. };
  48840. ArcRotateCamera.prototype.setPosition = function (position) {
  48841. if (this.position.equals(position)) {
  48842. return;
  48843. }
  48844. this.position.copyFrom(position);
  48845. this.rebuildAnglesAndRadius();
  48846. };
  48847. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48848. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48849. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48850. if (target.getBoundingInfo) {
  48851. if (toBoundingCenter) {
  48852. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48853. }
  48854. else {
  48855. this._targetBoundingCenter = null;
  48856. }
  48857. this._targetHost = target;
  48858. this._target = this._getTargetPosition();
  48859. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48860. }
  48861. else {
  48862. var newTarget = target;
  48863. var currentTarget = this._getTargetPosition();
  48864. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48865. return;
  48866. }
  48867. this._targetHost = null;
  48868. this._target = newTarget;
  48869. this._targetBoundingCenter = null;
  48870. this.onMeshTargetChangedObservable.notifyObservers(null);
  48871. }
  48872. this.rebuildAnglesAndRadius();
  48873. };
  48874. ArcRotateCamera.prototype._getViewMatrix = function () {
  48875. // Compute
  48876. var cosa = Math.cos(this.alpha);
  48877. var sina = Math.sin(this.alpha);
  48878. var cosb = Math.cos(this.beta);
  48879. var sinb = Math.sin(this.beta);
  48880. if (sinb === 0) {
  48881. sinb = 0.0001;
  48882. }
  48883. var target = this._getTargetPosition();
  48884. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48885. target.addToRef(this._computationVector, this._newPosition);
  48886. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48887. if (!this._collider) {
  48888. this._collider = new BABYLON.Collider();
  48889. }
  48890. this._collider._radius = this.collisionRadius;
  48891. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48892. this._collisionTriggered = true;
  48893. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48894. }
  48895. else {
  48896. this.position.copyFrom(this._newPosition);
  48897. var up = this.upVector;
  48898. if (this.allowUpsideDown && sinb < 0) {
  48899. up = up.clone();
  48900. up = up.negate();
  48901. }
  48902. this._computeViewMatrix(this.position, target, up);
  48903. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48904. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48905. }
  48906. this._currentTarget = target;
  48907. return this._viewMatrix;
  48908. };
  48909. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48910. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48911. meshes = meshes || this.getScene().meshes;
  48912. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48913. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48914. this.radius = distance * this.zoomOnFactor;
  48915. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48916. };
  48917. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48918. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48919. var meshesOrMinMaxVector;
  48920. var distance;
  48921. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48922. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48923. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48924. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48925. }
  48926. else { //minMaxVector and distance
  48927. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48928. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48929. distance = minMaxVectorAndDistance.distance;
  48930. }
  48931. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48932. if (!doNotUpdateMaxZ) {
  48933. this.maxZ = distance * 2;
  48934. }
  48935. };
  48936. /**
  48937. * @override
  48938. * Override Camera.createRigCamera
  48939. */
  48940. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48941. var alphaShift = 0;
  48942. switch (this.cameraRigMode) {
  48943. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48944. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48945. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48946. case BABYLON.Camera.RIG_MODE_VR:
  48947. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48948. break;
  48949. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48950. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48951. break;
  48952. }
  48953. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48954. rigCam._cameraRigParams = {};
  48955. return rigCam;
  48956. };
  48957. /**
  48958. * @override
  48959. * Override Camera._updateRigCameras
  48960. */
  48961. ArcRotateCamera.prototype._updateRigCameras = function () {
  48962. var camLeft = this._rigCameras[0];
  48963. var camRight = this._rigCameras[1];
  48964. camLeft.beta = camRight.beta = this.beta;
  48965. camLeft.radius = camRight.radius = this.radius;
  48966. switch (this.cameraRigMode) {
  48967. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48968. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48969. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48970. case BABYLON.Camera.RIG_MODE_VR:
  48971. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48972. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48973. break;
  48974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48975. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48976. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48977. break;
  48978. }
  48979. _super.prototype._updateRigCameras.call(this);
  48980. };
  48981. ArcRotateCamera.prototype.dispose = function () {
  48982. this.inputs.clear();
  48983. _super.prototype.dispose.call(this);
  48984. };
  48985. ArcRotateCamera.prototype.getClassName = function () {
  48986. return "ArcRotateCamera";
  48987. };
  48988. __decorate([
  48989. BABYLON.serialize()
  48990. ], ArcRotateCamera.prototype, "alpha", void 0);
  48991. __decorate([
  48992. BABYLON.serialize()
  48993. ], ArcRotateCamera.prototype, "beta", void 0);
  48994. __decorate([
  48995. BABYLON.serialize()
  48996. ], ArcRotateCamera.prototype, "radius", void 0);
  48997. __decorate([
  48998. BABYLON.serializeAsVector3("target")
  48999. ], ArcRotateCamera.prototype, "_target", void 0);
  49000. __decorate([
  49001. BABYLON.serialize()
  49002. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49003. __decorate([
  49004. BABYLON.serialize()
  49005. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49006. __decorate([
  49007. BABYLON.serialize()
  49008. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49009. __decorate([
  49010. BABYLON.serialize()
  49011. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49012. __decorate([
  49013. BABYLON.serialize()
  49014. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49015. __decorate([
  49016. BABYLON.serialize()
  49017. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49018. __decorate([
  49019. BABYLON.serialize()
  49020. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49021. __decorate([
  49022. BABYLON.serialize()
  49023. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49024. __decorate([
  49025. BABYLON.serialize()
  49026. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49027. __decorate([
  49028. BABYLON.serialize()
  49029. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49030. __decorate([
  49031. BABYLON.serialize()
  49032. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49033. __decorate([
  49034. BABYLON.serialize()
  49035. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49036. __decorate([
  49037. BABYLON.serialize()
  49038. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49039. __decorate([
  49040. BABYLON.serializeAsVector3()
  49041. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49042. __decorate([
  49043. BABYLON.serialize()
  49044. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49045. __decorate([
  49046. BABYLON.serialize()
  49047. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49048. __decorate([
  49049. BABYLON.serialize()
  49050. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49051. return ArcRotateCamera;
  49052. }(BABYLON.TargetCamera));
  49053. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49054. })(BABYLON || (BABYLON = {}));
  49055. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49056. var BABYLON;
  49057. (function (BABYLON) {
  49058. /**
  49059. * The HemisphericLight simulates the ambient environment light,
  49060. * so the passed direction is the light reflection direction, not the incoming direction.
  49061. */
  49062. var HemisphericLight = /** @class */ (function (_super) {
  49063. __extends(HemisphericLight, _super);
  49064. /**
  49065. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49066. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49067. * The HemisphericLight can't cast shadows.
  49068. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49069. * @param name The friendly name of the light
  49070. * @param direction The direction of the light reflection
  49071. * @param scene The scene the light belongs to
  49072. */
  49073. function HemisphericLight(name, direction, scene) {
  49074. var _this = _super.call(this, name, scene) || this;
  49075. /**
  49076. * The groundColor is the light in the opposite direction to the one specified during creation.
  49077. * 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.
  49078. */
  49079. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49080. _this.direction = direction || BABYLON.Vector3.Up();
  49081. return _this;
  49082. }
  49083. HemisphericLight.prototype._buildUniformLayout = function () {
  49084. this._uniformBuffer.addUniform("vLightData", 4);
  49085. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49086. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49087. this._uniformBuffer.addUniform("vLightGround", 3);
  49088. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49089. this._uniformBuffer.addUniform("depthValues", 2);
  49090. this._uniformBuffer.create();
  49091. };
  49092. /**
  49093. * Returns the string "HemisphericLight".
  49094. * @return The class name
  49095. */
  49096. HemisphericLight.prototype.getClassName = function () {
  49097. return "HemisphericLight";
  49098. };
  49099. /**
  49100. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49101. * Returns the updated direction.
  49102. * @param target The target the direction should point to
  49103. * @return The computed direction
  49104. */
  49105. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49106. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49107. return this.direction;
  49108. };
  49109. /**
  49110. * Returns the shadow generator associated to the light.
  49111. * @returns Always null for hemispheric lights because it does not support shadows.
  49112. */
  49113. HemisphericLight.prototype.getShadowGenerator = function () {
  49114. return null;
  49115. };
  49116. /**
  49117. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49118. * @param effect The effect to update
  49119. * @param lightIndex The index of the light in the effect to update
  49120. * @returns The hemispheric light
  49121. */
  49122. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49123. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49124. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49125. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49126. return this;
  49127. };
  49128. /**
  49129. * @hidden internal use only.
  49130. */
  49131. HemisphericLight.prototype._getWorldMatrix = function () {
  49132. if (!this._worldMatrix) {
  49133. this._worldMatrix = BABYLON.Matrix.Identity();
  49134. }
  49135. return this._worldMatrix;
  49136. };
  49137. /**
  49138. * Returns the integer 3.
  49139. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49140. */
  49141. HemisphericLight.prototype.getTypeID = function () {
  49142. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49143. };
  49144. __decorate([
  49145. BABYLON.serializeAsColor3()
  49146. ], HemisphericLight.prototype, "groundColor", void 0);
  49147. __decorate([
  49148. BABYLON.serializeAsVector3()
  49149. ], HemisphericLight.prototype, "direction", void 0);
  49150. return HemisphericLight;
  49151. }(BABYLON.Light));
  49152. BABYLON.HemisphericLight = HemisphericLight;
  49153. })(BABYLON || (BABYLON = {}));
  49154. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49155. var BABYLON;
  49156. (function (BABYLON) {
  49157. /**
  49158. * Base implementation IShadowLight
  49159. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49160. */
  49161. var ShadowLight = /** @class */ (function (_super) {
  49162. __extends(ShadowLight, _super);
  49163. function ShadowLight() {
  49164. var _this = _super !== null && _super.apply(this, arguments) || this;
  49165. _this._needProjectionMatrixCompute = true;
  49166. return _this;
  49167. }
  49168. ShadowLight.prototype._setPosition = function (value) {
  49169. this._position = value;
  49170. };
  49171. Object.defineProperty(ShadowLight.prototype, "position", {
  49172. /**
  49173. * Sets the position the shadow will be casted from. Also use as the light position for both
  49174. * point and spot lights.
  49175. */
  49176. get: function () {
  49177. return this._position;
  49178. },
  49179. /**
  49180. * Sets the position the shadow will be casted from. Also use as the light position for both
  49181. * point and spot lights.
  49182. */
  49183. set: function (value) {
  49184. this._setPosition(value);
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. ShadowLight.prototype._setDirection = function (value) {
  49190. this._direction = value;
  49191. };
  49192. Object.defineProperty(ShadowLight.prototype, "direction", {
  49193. /**
  49194. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49195. * Also use as the light direction on spot and directional lights.
  49196. */
  49197. get: function () {
  49198. return this._direction;
  49199. },
  49200. /**
  49201. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49202. * Also use as the light direction on spot and directional lights.
  49203. */
  49204. set: function (value) {
  49205. this._setDirection(value);
  49206. },
  49207. enumerable: true,
  49208. configurable: true
  49209. });
  49210. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49211. /**
  49212. * Gets the shadow projection clipping minimum z value.
  49213. */
  49214. get: function () {
  49215. return this._shadowMinZ;
  49216. },
  49217. /**
  49218. * Sets the shadow projection clipping minimum z value.
  49219. */
  49220. set: function (value) {
  49221. this._shadowMinZ = value;
  49222. this.forceProjectionMatrixCompute();
  49223. },
  49224. enumerable: true,
  49225. configurable: true
  49226. });
  49227. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49228. /**
  49229. * Sets the shadow projection clipping maximum z value.
  49230. */
  49231. get: function () {
  49232. return this._shadowMaxZ;
  49233. },
  49234. /**
  49235. * Gets the shadow projection clipping maximum z value.
  49236. */
  49237. set: function (value) {
  49238. this._shadowMaxZ = value;
  49239. this.forceProjectionMatrixCompute();
  49240. },
  49241. enumerable: true,
  49242. configurable: true
  49243. });
  49244. /**
  49245. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49246. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49247. */
  49248. ShadowLight.prototype.computeTransformedInformation = function () {
  49249. if (this.parent && this.parent.getWorldMatrix) {
  49250. if (!this.transformedPosition) {
  49251. this.transformedPosition = BABYLON.Vector3.Zero();
  49252. }
  49253. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49254. // In case the direction is present.
  49255. if (this.direction) {
  49256. if (!this.transformedDirection) {
  49257. this.transformedDirection = BABYLON.Vector3.Zero();
  49258. }
  49259. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49260. }
  49261. return true;
  49262. }
  49263. return false;
  49264. };
  49265. /**
  49266. * Return the depth scale used for the shadow map.
  49267. * @returns the depth scale.
  49268. */
  49269. ShadowLight.prototype.getDepthScale = function () {
  49270. return 50.0;
  49271. };
  49272. /**
  49273. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49274. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49275. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49276. */
  49277. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49278. return this.transformedDirection ? this.transformedDirection : this.direction;
  49279. };
  49280. /**
  49281. * Returns the ShadowLight absolute position in the World.
  49282. * @returns the position vector in world space
  49283. */
  49284. ShadowLight.prototype.getAbsolutePosition = function () {
  49285. return this.transformedPosition ? this.transformedPosition : this.position;
  49286. };
  49287. /**
  49288. * Sets the ShadowLight direction toward the passed target.
  49289. * @param target The point tot target in local space
  49290. * @returns the updated ShadowLight direction
  49291. */
  49292. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49293. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49294. return this.direction;
  49295. };
  49296. /**
  49297. * Returns the light rotation in euler definition.
  49298. * @returns the x y z rotation in local space.
  49299. */
  49300. ShadowLight.prototype.getRotation = function () {
  49301. this.direction.normalize();
  49302. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49303. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49304. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49305. };
  49306. /**
  49307. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49308. * @returns true if a cube texture needs to be use
  49309. */
  49310. ShadowLight.prototype.needCube = function () {
  49311. return false;
  49312. };
  49313. /**
  49314. * Detects if the projection matrix requires to be recomputed this frame.
  49315. * @returns true if it requires to be recomputed otherwise, false.
  49316. */
  49317. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49318. return this._needProjectionMatrixCompute;
  49319. };
  49320. /**
  49321. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49322. */
  49323. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49324. this._needProjectionMatrixCompute = true;
  49325. };
  49326. /**
  49327. * Get the world matrix of the sahdow lights.
  49328. * @hidden Internal Use Only
  49329. */
  49330. ShadowLight.prototype._getWorldMatrix = function () {
  49331. if (!this._worldMatrix) {
  49332. this._worldMatrix = BABYLON.Matrix.Identity();
  49333. }
  49334. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49335. return this._worldMatrix;
  49336. };
  49337. /**
  49338. * Gets the minZ used for shadow according to both the scene and the light.
  49339. * @param activeCamera The camera we are returning the min for
  49340. * @returns the depth min z
  49341. */
  49342. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49343. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49344. };
  49345. /**
  49346. * Gets the maxZ used for shadow according to both the scene and the light.
  49347. * @param activeCamera The camera we are returning the max for
  49348. * @returns the depth max z
  49349. */
  49350. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49351. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49352. };
  49353. /**
  49354. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49355. * @param matrix The materix to updated with the projection information
  49356. * @param viewMatrix The transform matrix of the light
  49357. * @param renderList The list of mesh to render in the map
  49358. * @returns The current light
  49359. */
  49360. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49361. if (this.customProjectionMatrixBuilder) {
  49362. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49363. }
  49364. else {
  49365. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49366. }
  49367. return this;
  49368. };
  49369. __decorate([
  49370. BABYLON.serializeAsVector3()
  49371. ], ShadowLight.prototype, "position", null);
  49372. __decorate([
  49373. BABYLON.serializeAsVector3()
  49374. ], ShadowLight.prototype, "direction", null);
  49375. __decorate([
  49376. BABYLON.serialize()
  49377. ], ShadowLight.prototype, "shadowMinZ", null);
  49378. __decorate([
  49379. BABYLON.serialize()
  49380. ], ShadowLight.prototype, "shadowMaxZ", null);
  49381. return ShadowLight;
  49382. }(BABYLON.Light));
  49383. BABYLON.ShadowLight = ShadowLight;
  49384. })(BABYLON || (BABYLON = {}));
  49385. //# sourceMappingURL=babylon.shadowLight.js.map
  49386. var BABYLON;
  49387. (function (BABYLON) {
  49388. /**
  49389. * A point light is a light defined by an unique point in world space.
  49390. * The light is emitted in every direction from this point.
  49391. * A good example of a point light is a standard light bulb.
  49392. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49393. */
  49394. var PointLight = /** @class */ (function (_super) {
  49395. __extends(PointLight, _super);
  49396. /**
  49397. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49398. * A PointLight emits the light in every direction.
  49399. * It can cast shadows.
  49400. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49401. * ```javascript
  49402. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49403. * ```
  49404. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49405. * @param name The light friendly name
  49406. * @param position The position of the point light in the scene
  49407. * @param scene The scene the lights belongs to
  49408. */
  49409. function PointLight(name, position, scene) {
  49410. var _this = _super.call(this, name, scene) || this;
  49411. _this._shadowAngle = Math.PI / 2;
  49412. _this.position = position;
  49413. return _this;
  49414. }
  49415. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49416. /**
  49417. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49418. * This specifies what angle the shadow will use to be created.
  49419. *
  49420. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49421. */
  49422. get: function () {
  49423. return this._shadowAngle;
  49424. },
  49425. /**
  49426. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49427. * This specifies what angle the shadow will use to be created.
  49428. *
  49429. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49430. */
  49431. set: function (value) {
  49432. this._shadowAngle = value;
  49433. this.forceProjectionMatrixCompute();
  49434. },
  49435. enumerable: true,
  49436. configurable: true
  49437. });
  49438. Object.defineProperty(PointLight.prototype, "direction", {
  49439. /**
  49440. * Gets the direction if it has been set.
  49441. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49442. */
  49443. get: function () {
  49444. return this._direction;
  49445. },
  49446. /**
  49447. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49448. */
  49449. set: function (value) {
  49450. var previousNeedCube = this.needCube();
  49451. this._direction = value;
  49452. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49453. this._shadowGenerator.recreateShadowMap();
  49454. }
  49455. },
  49456. enumerable: true,
  49457. configurable: true
  49458. });
  49459. /**
  49460. * Returns the string "PointLight"
  49461. * @returns the class name
  49462. */
  49463. PointLight.prototype.getClassName = function () {
  49464. return "PointLight";
  49465. };
  49466. /**
  49467. * Returns the integer 0.
  49468. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49469. */
  49470. PointLight.prototype.getTypeID = function () {
  49471. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49472. };
  49473. /**
  49474. * Specifies wether or not the shadowmap should be a cube texture.
  49475. * @returns true if the shadowmap needs to be a cube texture.
  49476. */
  49477. PointLight.prototype.needCube = function () {
  49478. return !this.direction;
  49479. };
  49480. /**
  49481. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49482. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49483. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49484. */
  49485. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49486. if (this.direction) {
  49487. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49488. }
  49489. else {
  49490. switch (faceIndex) {
  49491. case 0:
  49492. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49493. case 1:
  49494. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49495. case 2:
  49496. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49497. case 3:
  49498. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49499. case 4:
  49500. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49501. case 5:
  49502. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49503. }
  49504. }
  49505. return BABYLON.Vector3.Zero();
  49506. };
  49507. /**
  49508. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49509. * - fov = PI / 2
  49510. * - aspect ratio : 1.0
  49511. * - z-near and far equal to the active camera minZ and maxZ.
  49512. * Returns the PointLight.
  49513. */
  49514. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49515. var activeCamera = this.getScene().activeCamera;
  49516. if (!activeCamera) {
  49517. return;
  49518. }
  49519. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49520. };
  49521. PointLight.prototype._buildUniformLayout = function () {
  49522. this._uniformBuffer.addUniform("vLightData", 4);
  49523. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49524. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49525. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49526. this._uniformBuffer.addUniform("depthValues", 2);
  49527. this._uniformBuffer.create();
  49528. };
  49529. /**
  49530. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49531. * @param effect The effect to update
  49532. * @param lightIndex The index of the light in the effect to update
  49533. * @returns The point light
  49534. */
  49535. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49536. if (this.computeTransformedInformation()) {
  49537. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49538. return this;
  49539. }
  49540. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49541. return this;
  49542. };
  49543. __decorate([
  49544. BABYLON.serialize()
  49545. ], PointLight.prototype, "shadowAngle", null);
  49546. return PointLight;
  49547. }(BABYLON.ShadowLight));
  49548. BABYLON.PointLight = PointLight;
  49549. })(BABYLON || (BABYLON = {}));
  49550. //# sourceMappingURL=babylon.pointLight.js.map
  49551. var BABYLON;
  49552. (function (BABYLON) {
  49553. /**
  49554. * A directional light is defined by a direction (what a surprise!).
  49555. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49556. * 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.
  49557. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49558. */
  49559. var DirectionalLight = /** @class */ (function (_super) {
  49560. __extends(DirectionalLight, _super);
  49561. /**
  49562. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49563. * The directional light is emitted from everywhere in the given direction.
  49564. * It can cast shawdows.
  49565. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49566. * @param name The friendly name of the light
  49567. * @param direction The direction of the light
  49568. * @param scene The scene the light belongs to
  49569. */
  49570. function DirectionalLight(name, direction, scene) {
  49571. var _this = _super.call(this, name, scene) || this;
  49572. _this._shadowFrustumSize = 0;
  49573. _this._shadowOrthoScale = 0.1;
  49574. /**
  49575. * Automatically compute the projection matrix to best fit (including all the casters)
  49576. * on each frame.
  49577. */
  49578. _this.autoUpdateExtends = true;
  49579. // Cache
  49580. _this._orthoLeft = Number.MAX_VALUE;
  49581. _this._orthoRight = Number.MIN_VALUE;
  49582. _this._orthoTop = Number.MIN_VALUE;
  49583. _this._orthoBottom = Number.MAX_VALUE;
  49584. _this.position = direction.scale(-1.0);
  49585. _this.direction = direction;
  49586. return _this;
  49587. }
  49588. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49589. /**
  49590. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49591. */
  49592. get: function () {
  49593. return this._shadowFrustumSize;
  49594. },
  49595. /**
  49596. * Specifies a fix frustum size for the shadow generation.
  49597. */
  49598. set: function (value) {
  49599. this._shadowFrustumSize = value;
  49600. this.forceProjectionMatrixCompute();
  49601. },
  49602. enumerable: true,
  49603. configurable: true
  49604. });
  49605. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49606. /**
  49607. * Gets the shadow projection scale against the optimal computed one.
  49608. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49609. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49610. */
  49611. get: function () {
  49612. return this._shadowOrthoScale;
  49613. },
  49614. /**
  49615. * Sets the shadow projection scale against the optimal computed one.
  49616. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49617. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49618. */
  49619. set: function (value) {
  49620. this._shadowOrthoScale = value;
  49621. this.forceProjectionMatrixCompute();
  49622. },
  49623. enumerable: true,
  49624. configurable: true
  49625. });
  49626. /**
  49627. * Returns the string "DirectionalLight".
  49628. * @return The class name
  49629. */
  49630. DirectionalLight.prototype.getClassName = function () {
  49631. return "DirectionalLight";
  49632. };
  49633. /**
  49634. * Returns the integer 1.
  49635. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49636. */
  49637. DirectionalLight.prototype.getTypeID = function () {
  49638. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49639. };
  49640. /**
  49641. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49642. * Returns the DirectionalLight Shadow projection matrix.
  49643. */
  49644. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49645. if (this.shadowFrustumSize > 0) {
  49646. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49647. }
  49648. else {
  49649. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49650. }
  49651. };
  49652. /**
  49653. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49654. * Returns the DirectionalLight Shadow projection matrix.
  49655. */
  49656. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49657. var activeCamera = this.getScene().activeCamera;
  49658. if (!activeCamera) {
  49659. return;
  49660. }
  49661. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49662. };
  49663. /**
  49664. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49665. * Returns the DirectionalLight Shadow projection matrix.
  49666. */
  49667. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49668. var activeCamera = this.getScene().activeCamera;
  49669. if (!activeCamera) {
  49670. return;
  49671. }
  49672. // Check extends
  49673. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49674. var tempVector3 = BABYLON.Vector3.Zero();
  49675. this._orthoLeft = Number.MAX_VALUE;
  49676. this._orthoRight = Number.MIN_VALUE;
  49677. this._orthoTop = Number.MIN_VALUE;
  49678. this._orthoBottom = Number.MAX_VALUE;
  49679. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49680. var mesh = renderList[meshIndex];
  49681. if (!mesh) {
  49682. continue;
  49683. }
  49684. var boundingInfo = mesh.getBoundingInfo();
  49685. var boundingBox = boundingInfo.boundingBox;
  49686. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49687. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49688. if (tempVector3.x < this._orthoLeft)
  49689. this._orthoLeft = tempVector3.x;
  49690. if (tempVector3.y < this._orthoBottom)
  49691. this._orthoBottom = tempVector3.y;
  49692. if (tempVector3.x > this._orthoRight)
  49693. this._orthoRight = tempVector3.x;
  49694. if (tempVector3.y > this._orthoTop)
  49695. this._orthoTop = tempVector3.y;
  49696. }
  49697. }
  49698. }
  49699. var xOffset = this._orthoRight - this._orthoLeft;
  49700. var yOffset = this._orthoTop - this._orthoBottom;
  49701. 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);
  49702. };
  49703. DirectionalLight.prototype._buildUniformLayout = function () {
  49704. this._uniformBuffer.addUniform("vLightData", 4);
  49705. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49706. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49707. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49708. this._uniformBuffer.addUniform("depthValues", 2);
  49709. this._uniformBuffer.create();
  49710. };
  49711. /**
  49712. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49713. * @param effect The effect to update
  49714. * @param lightIndex The index of the light in the effect to update
  49715. * @returns The directional light
  49716. */
  49717. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49718. if (this.computeTransformedInformation()) {
  49719. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49720. return this;
  49721. }
  49722. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49723. return this;
  49724. };
  49725. /**
  49726. * Gets the minZ used for shadow according to both the scene and the light.
  49727. *
  49728. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49729. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49730. * @param activeCamera The camera we are returning the min for
  49731. * @returns the depth min z
  49732. */
  49733. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49734. return 1;
  49735. };
  49736. /**
  49737. * Gets the maxZ used for shadow according to both the scene and the light.
  49738. *
  49739. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49740. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49741. * @param activeCamera The camera we are returning the max for
  49742. * @returns the depth max z
  49743. */
  49744. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49745. return 1;
  49746. };
  49747. __decorate([
  49748. BABYLON.serialize()
  49749. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49750. __decorate([
  49751. BABYLON.serialize()
  49752. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49753. __decorate([
  49754. BABYLON.serialize()
  49755. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49756. return DirectionalLight;
  49757. }(BABYLON.ShadowLight));
  49758. BABYLON.DirectionalLight = DirectionalLight;
  49759. })(BABYLON || (BABYLON = {}));
  49760. //# sourceMappingURL=babylon.directionalLight.js.map
  49761. var BABYLON;
  49762. (function (BABYLON) {
  49763. /**
  49764. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49765. * These values define a cone of light starting from the position, emitting toward the direction.
  49766. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49767. * and the exponent defines the speed of the decay of the light with distance (reach).
  49768. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49769. */
  49770. var SpotLight = /** @class */ (function (_super) {
  49771. __extends(SpotLight, _super);
  49772. /**
  49773. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49774. * It can cast shadows.
  49775. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49776. * @param name The light friendly name
  49777. * @param position The position of the spot light in the scene
  49778. * @param direction The direction of the light in the scene
  49779. * @param angle The cone angle of the light in Radians
  49780. * @param exponent The light decay speed with the distance from the emission spot
  49781. * @param scene The scene the lights belongs to
  49782. */
  49783. function SpotLight(name, position, direction, angle, exponent, scene) {
  49784. var _this = _super.call(this, name, scene) || this;
  49785. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49786. _this._projectionTextureLightNear = 1e-6;
  49787. _this._projectionTextureLightFar = 1000.0;
  49788. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49789. _this._projectionTextureViewLightDirty = true;
  49790. _this._projectionTextureProjectionLightDirty = true;
  49791. _this._projectionTextureDirty = true;
  49792. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49793. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49794. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49795. _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);
  49796. _this.position = position;
  49797. _this.direction = direction;
  49798. _this.angle = angle;
  49799. _this.exponent = exponent;
  49800. return _this;
  49801. }
  49802. Object.defineProperty(SpotLight.prototype, "angle", {
  49803. /**
  49804. * Gets the cone angle of the spot light in Radians.
  49805. */
  49806. get: function () {
  49807. return this._angle;
  49808. },
  49809. /**
  49810. * Sets the cone angle of the spot light in Radians.
  49811. */
  49812. set: function (value) {
  49813. this._angle = value;
  49814. this._projectionTextureProjectionLightDirty = true;
  49815. this.forceProjectionMatrixCompute();
  49816. },
  49817. enumerable: true,
  49818. configurable: true
  49819. });
  49820. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49821. /**
  49822. * Allows scaling the angle of the light for shadow generation only.
  49823. */
  49824. get: function () {
  49825. return this._shadowAngleScale;
  49826. },
  49827. /**
  49828. * Allows scaling the angle of the light for shadow generation only.
  49829. */
  49830. set: function (value) {
  49831. this._shadowAngleScale = value;
  49832. this.forceProjectionMatrixCompute();
  49833. },
  49834. enumerable: true,
  49835. configurable: true
  49836. });
  49837. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49838. /**
  49839. * Allows reading the projecton texture
  49840. */
  49841. get: function () {
  49842. return this._projectionTextureMatrix;
  49843. },
  49844. enumerable: true,
  49845. configurable: true
  49846. });
  49847. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49848. /**
  49849. * Gets the near clip of the Spotlight for texture projection.
  49850. */
  49851. get: function () {
  49852. return this._projectionTextureLightNear;
  49853. },
  49854. /**
  49855. * Sets the near clip of the Spotlight for texture projection.
  49856. */
  49857. set: function (value) {
  49858. this._projectionTextureLightNear = value;
  49859. this._projectionTextureProjectionLightDirty = true;
  49860. },
  49861. enumerable: true,
  49862. configurable: true
  49863. });
  49864. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49865. /**
  49866. * Gets the far clip of the Spotlight for texture projection.
  49867. */
  49868. get: function () {
  49869. return this._projectionTextureLightFar;
  49870. },
  49871. /**
  49872. * Sets the far clip of the Spotlight for texture projection.
  49873. */
  49874. set: function (value) {
  49875. this._projectionTextureLightFar = value;
  49876. this._projectionTextureProjectionLightDirty = true;
  49877. },
  49878. enumerable: true,
  49879. configurable: true
  49880. });
  49881. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49882. /**
  49883. * Gets the Up vector of the Spotlight for texture projection.
  49884. */
  49885. get: function () {
  49886. return this._projectionTextureUpDirection;
  49887. },
  49888. /**
  49889. * Sets the Up vector of the Spotlight for texture projection.
  49890. */
  49891. set: function (value) {
  49892. this._projectionTextureUpDirection = value;
  49893. this._projectionTextureProjectionLightDirty = true;
  49894. },
  49895. enumerable: true,
  49896. configurable: true
  49897. });
  49898. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49899. /**
  49900. * Gets the projection texture of the light.
  49901. */
  49902. get: function () {
  49903. return this._projectionTexture;
  49904. },
  49905. /**
  49906. * Sets the projection texture of the light.
  49907. */
  49908. set: function (value) {
  49909. this._projectionTexture = value;
  49910. this._projectionTextureDirty = true;
  49911. },
  49912. enumerable: true,
  49913. configurable: true
  49914. });
  49915. /**
  49916. * Returns the string "SpotLight".
  49917. * @returns the class name
  49918. */
  49919. SpotLight.prototype.getClassName = function () {
  49920. return "SpotLight";
  49921. };
  49922. /**
  49923. * Returns the integer 2.
  49924. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49925. */
  49926. SpotLight.prototype.getTypeID = function () {
  49927. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49928. };
  49929. /**
  49930. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49931. */
  49932. SpotLight.prototype._setDirection = function (value) {
  49933. _super.prototype._setDirection.call(this, value);
  49934. this._projectionTextureViewLightDirty = true;
  49935. };
  49936. /**
  49937. * Overrides the position setter to recompute the projection texture view light Matrix.
  49938. */
  49939. SpotLight.prototype._setPosition = function (value) {
  49940. _super.prototype._setPosition.call(this, value);
  49941. this._projectionTextureViewLightDirty = true;
  49942. };
  49943. /**
  49944. * 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.
  49945. * Returns the SpotLight.
  49946. */
  49947. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49948. var activeCamera = this.getScene().activeCamera;
  49949. if (!activeCamera) {
  49950. return;
  49951. }
  49952. this._shadowAngleScale = this._shadowAngleScale || 1;
  49953. var angle = this._shadowAngleScale * this._angle;
  49954. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49955. };
  49956. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49957. this._projectionTextureViewLightDirty = false;
  49958. this._projectionTextureDirty = true;
  49959. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49960. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49961. };
  49962. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49963. this._projectionTextureProjectionLightDirty = false;
  49964. this._projectionTextureDirty = true;
  49965. var light_far = this.projectionTextureLightFar;
  49966. var light_near = this.projectionTextureLightNear;
  49967. var P = light_far / (light_far - light_near);
  49968. var Q = -P * light_near;
  49969. var S = 1.0 / Math.tan(this._angle / 2.0);
  49970. var A = 1.0;
  49971. 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);
  49972. };
  49973. /**
  49974. * Main function for light texture projection matrix computing.
  49975. */
  49976. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49977. this._projectionTextureDirty = false;
  49978. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49979. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49980. };
  49981. SpotLight.prototype._buildUniformLayout = function () {
  49982. this._uniformBuffer.addUniform("vLightData", 4);
  49983. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49984. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49985. this._uniformBuffer.addUniform("vLightDirection", 3);
  49986. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49987. this._uniformBuffer.addUniform("depthValues", 2);
  49988. this._uniformBuffer.create();
  49989. };
  49990. /**
  49991. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49992. * @param effect The effect to update
  49993. * @param lightIndex The index of the light in the effect to update
  49994. * @returns The spot light
  49995. */
  49996. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49997. var normalizeDirection;
  49998. if (this.computeTransformedInformation()) {
  49999. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50000. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50001. }
  50002. else {
  50003. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50004. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50005. }
  50006. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50007. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50008. if (this._projectionTextureViewLightDirty) {
  50009. this._computeProjectionTextureViewLightMatrix();
  50010. }
  50011. if (this._projectionTextureProjectionLightDirty) {
  50012. this._computeProjectionTextureProjectionLightMatrix();
  50013. }
  50014. if (this._projectionTextureDirty) {
  50015. this._computeProjectionTextureMatrix();
  50016. }
  50017. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50018. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50019. }
  50020. return this;
  50021. };
  50022. /**
  50023. * Disposes the light and the associated resources.
  50024. */
  50025. SpotLight.prototype.dispose = function () {
  50026. _super.prototype.dispose.call(this);
  50027. if (this._projectionTexture) {
  50028. this._projectionTexture.dispose();
  50029. }
  50030. };
  50031. __decorate([
  50032. BABYLON.serialize()
  50033. ], SpotLight.prototype, "angle", null);
  50034. __decorate([
  50035. BABYLON.serialize()
  50036. ], SpotLight.prototype, "shadowAngleScale", null);
  50037. __decorate([
  50038. BABYLON.serialize()
  50039. ], SpotLight.prototype, "exponent", void 0);
  50040. __decorate([
  50041. BABYLON.serialize()
  50042. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50043. __decorate([
  50044. BABYLON.serialize()
  50045. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50046. __decorate([
  50047. BABYLON.serialize()
  50048. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50049. __decorate([
  50050. BABYLON.serializeAsTexture("projectedLightTexture")
  50051. ], SpotLight.prototype, "_projectionTexture", void 0);
  50052. return SpotLight;
  50053. }(BABYLON.ShadowLight));
  50054. BABYLON.SpotLight = SpotLight;
  50055. })(BABYLON || (BABYLON = {}));
  50056. //# sourceMappingURL=babylon.spotLight.js.map
  50057. var BABYLON;
  50058. (function (BABYLON) {
  50059. /**
  50060. * Class used to override all child animations of a given target
  50061. */
  50062. var AnimationPropertiesOverride = /** @class */ (function () {
  50063. function AnimationPropertiesOverride() {
  50064. /**
  50065. * Gets or sets a value indicating if animation blending must be used
  50066. */
  50067. this.enableBlending = false;
  50068. /**
  50069. * Gets or sets the blending speed to use when enableBlending is true
  50070. */
  50071. this.blendingSpeed = 0.01;
  50072. /**
  50073. * Gets or sets the default loop mode to use
  50074. */
  50075. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50076. }
  50077. return AnimationPropertiesOverride;
  50078. }());
  50079. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50080. })(BABYLON || (BABYLON = {}));
  50081. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50082. var BABYLON;
  50083. (function (BABYLON) {
  50084. /**
  50085. * Represents the range of an animation
  50086. */
  50087. var AnimationRange = /** @class */ (function () {
  50088. /**
  50089. * Initializes the range of an animation
  50090. * @param name The name of the animation range
  50091. * @param from The starting frame of the animation
  50092. * @param to The ending frame of the animation
  50093. */
  50094. function AnimationRange(
  50095. /**The name of the animation range**/
  50096. name,
  50097. /**The starting frame of the animation */
  50098. from,
  50099. /**The ending frame of the animation*/
  50100. to) {
  50101. this.name = name;
  50102. this.from = from;
  50103. this.to = to;
  50104. }
  50105. /**
  50106. * Makes a copy of the animation range
  50107. * @returns A copy of the animation range
  50108. */
  50109. AnimationRange.prototype.clone = function () {
  50110. return new AnimationRange(this.name, this.from, this.to);
  50111. };
  50112. return AnimationRange;
  50113. }());
  50114. BABYLON.AnimationRange = AnimationRange;
  50115. /**
  50116. * Composed of a frame, and an action function
  50117. */
  50118. var AnimationEvent = /** @class */ (function () {
  50119. /**
  50120. * Initializes the animation event
  50121. * @param frame The frame for which the event is triggered
  50122. * @param action The event to perform when triggered
  50123. * @param onlyOnce Specifies if the event should be triggered only once
  50124. */
  50125. function AnimationEvent(
  50126. /** The frame for which the event is triggered **/
  50127. frame,
  50128. /** The event to perform when triggered **/
  50129. action,
  50130. /** Specifies if the event should be triggered only once**/
  50131. onlyOnce) {
  50132. this.frame = frame;
  50133. this.action = action;
  50134. this.onlyOnce = onlyOnce;
  50135. /**
  50136. * Specifies if the animation event is done
  50137. */
  50138. this.isDone = false;
  50139. }
  50140. return AnimationEvent;
  50141. }());
  50142. BABYLON.AnimationEvent = AnimationEvent;
  50143. /**
  50144. * A cursor which tracks a point on a path
  50145. */
  50146. var PathCursor = /** @class */ (function () {
  50147. /**
  50148. * Initializes the path cursor
  50149. * @param path The path to track
  50150. */
  50151. function PathCursor(path) {
  50152. this.path = path;
  50153. /**
  50154. * Stores path cursor callbacks for when an onchange event is triggered
  50155. */
  50156. this._onchange = new Array();
  50157. /**
  50158. * The value of the path cursor
  50159. */
  50160. this.value = 0;
  50161. /**
  50162. * The animation array of the path cursor
  50163. */
  50164. this.animations = new Array();
  50165. }
  50166. /**
  50167. * Gets the cursor point on the path
  50168. * @returns A point on the path cursor at the cursor location
  50169. */
  50170. PathCursor.prototype.getPoint = function () {
  50171. var point = this.path.getPointAtLengthPosition(this.value);
  50172. return new BABYLON.Vector3(point.x, 0, point.y);
  50173. };
  50174. /**
  50175. * Moves the cursor ahead by the step amount
  50176. * @param step The amount to move the cursor forward
  50177. * @returns This path cursor
  50178. */
  50179. PathCursor.prototype.moveAhead = function (step) {
  50180. if (step === void 0) { step = 0.002; }
  50181. this.move(step);
  50182. return this;
  50183. };
  50184. /**
  50185. * Moves the cursor behind by the step amount
  50186. * @param step The amount to move the cursor back
  50187. * @returns This path cursor
  50188. */
  50189. PathCursor.prototype.moveBack = function (step) {
  50190. if (step === void 0) { step = 0.002; }
  50191. this.move(-step);
  50192. return this;
  50193. };
  50194. /**
  50195. * Moves the cursor by the step amount
  50196. * If the step amount is greater than one, an exception is thrown
  50197. * @param step The amount to move the cursor
  50198. * @returns This path cursor
  50199. */
  50200. PathCursor.prototype.move = function (step) {
  50201. if (Math.abs(step) > 1) {
  50202. throw "step size should be less than 1.";
  50203. }
  50204. this.value += step;
  50205. this.ensureLimits();
  50206. this.raiseOnChange();
  50207. return this;
  50208. };
  50209. /**
  50210. * Ensures that the value is limited between zero and one
  50211. * @returns This path cursor
  50212. */
  50213. PathCursor.prototype.ensureLimits = function () {
  50214. while (this.value > 1) {
  50215. this.value -= 1;
  50216. }
  50217. while (this.value < 0) {
  50218. this.value += 1;
  50219. }
  50220. return this;
  50221. };
  50222. /**
  50223. * Runs onchange callbacks on change (used by the animation engine)
  50224. * @returns This path cursor
  50225. */
  50226. PathCursor.prototype.raiseOnChange = function () {
  50227. var _this = this;
  50228. this._onchange.forEach(function (f) { return f(_this); });
  50229. return this;
  50230. };
  50231. /**
  50232. * Executes a function on change
  50233. * @param f A path cursor onchange callback
  50234. * @returns This path cursor
  50235. */
  50236. PathCursor.prototype.onchange = function (f) {
  50237. this._onchange.push(f);
  50238. return this;
  50239. };
  50240. return PathCursor;
  50241. }());
  50242. BABYLON.PathCursor = PathCursor;
  50243. /**
  50244. * Enum for the animation key frame interpolation type
  50245. */
  50246. var AnimationKeyInterpolation;
  50247. (function (AnimationKeyInterpolation) {
  50248. /**
  50249. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50250. */
  50251. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50252. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50253. /**
  50254. * Class used to store any kind of animation
  50255. */
  50256. var Animation = /** @class */ (function () {
  50257. /**
  50258. * Initializes the animation
  50259. * @param name Name of the animation
  50260. * @param targetProperty Property to animate
  50261. * @param framePerSecond The frames per second of the animation
  50262. * @param dataType The data type of the animation
  50263. * @param loopMode The loop mode of the animation
  50264. * @param enableBlendings Specifies if blending should be enabled
  50265. */
  50266. function Animation(
  50267. /**Name of the animation */
  50268. name,
  50269. /**Property to animate */
  50270. targetProperty,
  50271. /**The frames per second of the animation */
  50272. framePerSecond,
  50273. /**The data type of the animation */
  50274. dataType,
  50275. /**The loop mode of the animation */
  50276. loopMode,
  50277. /**Specifies if blending should be enabled */
  50278. enableBlending) {
  50279. this.name = name;
  50280. this.targetProperty = targetProperty;
  50281. this.framePerSecond = framePerSecond;
  50282. this.dataType = dataType;
  50283. this.loopMode = loopMode;
  50284. this.enableBlending = enableBlending;
  50285. /**
  50286. * @hidden Internal use only
  50287. */
  50288. this._runtimeAnimations = new Array();
  50289. /**
  50290. * The set of event that will be linked to this animation
  50291. */
  50292. this._events = new Array();
  50293. /**
  50294. * Stores the blending speed of the animation
  50295. */
  50296. this.blendingSpeed = 0.01;
  50297. /**
  50298. * Stores the animation ranges for the animation
  50299. */
  50300. this._ranges = {};
  50301. this.targetPropertyPath = targetProperty.split(".");
  50302. this.dataType = dataType;
  50303. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50304. }
  50305. /**
  50306. * @hidden Internal use
  50307. */
  50308. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50309. var dataType = undefined;
  50310. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50311. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50312. }
  50313. else if (from instanceof BABYLON.Quaternion) {
  50314. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50315. }
  50316. else if (from instanceof BABYLON.Vector3) {
  50317. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50318. }
  50319. else if (from instanceof BABYLON.Vector2) {
  50320. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50321. }
  50322. else if (from instanceof BABYLON.Color3) {
  50323. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50324. }
  50325. else if (from instanceof BABYLON.Size) {
  50326. dataType = Animation.ANIMATIONTYPE_SIZE;
  50327. }
  50328. if (dataType == undefined) {
  50329. return null;
  50330. }
  50331. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50332. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50333. animation.setKeys(keys);
  50334. if (easingFunction !== undefined) {
  50335. animation.setEasingFunction(easingFunction);
  50336. }
  50337. return animation;
  50338. };
  50339. /**
  50340. * Sets up an animation
  50341. * @param property The property to animate
  50342. * @param animationType The animation type to apply
  50343. * @param framePerSecond The frames per second of the animation
  50344. * @param easingFunction The easing function used in the animation
  50345. * @returns The created animation
  50346. */
  50347. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50348. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50349. animation.setEasingFunction(easingFunction);
  50350. return animation;
  50351. };
  50352. /**
  50353. * Create and start an animation on a node
  50354. * @param name defines the name of the global animation that will be run on all nodes
  50355. * @param node defines the root node where the animation will take place
  50356. * @param targetProperty defines property to animate
  50357. * @param framePerSecond defines the number of frame per second yo use
  50358. * @param totalFrame defines the number of frames in total
  50359. * @param from defines the initial value
  50360. * @param to defines the final value
  50361. * @param loopMode defines which loop mode you want to use (off by default)
  50362. * @param easingFunction defines the easing function to use (linear by default)
  50363. * @param onAnimationEnd defines the callback to call when animation end
  50364. * @returns the animatable created for this animation
  50365. */
  50366. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50367. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50368. if (!animation) {
  50369. return null;
  50370. }
  50371. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50372. };
  50373. /**
  50374. * Create and start an animation on a node and its descendants
  50375. * @param name defines the name of the global animation that will be run on all nodes
  50376. * @param node defines the root node where the animation will take place
  50377. * @param 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
  50378. * @param targetProperty defines property to animate
  50379. * @param framePerSecond defines the number of frame per second to use
  50380. * @param totalFrame defines the number of frames in total
  50381. * @param from defines the initial value
  50382. * @param to defines the final value
  50383. * @param loopMode defines which loop mode you want to use (off by default)
  50384. * @param easingFunction defines the easing function to use (linear by default)
  50385. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50386. * @returns the list of animatables created for all nodes
  50387. * @example https://www.babylonjs-playground.com/#MH0VLI
  50388. */
  50389. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50390. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50391. if (!animation) {
  50392. return null;
  50393. }
  50394. var scene = node.getScene();
  50395. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50396. };
  50397. /**
  50398. * Creates a new animation, merges it with the existing animations and starts it
  50399. * @param name Name of the animation
  50400. * @param node Node which contains the scene that begins the animations
  50401. * @param targetProperty Specifies which property to animate
  50402. * @param framePerSecond The frames per second of the animation
  50403. * @param totalFrame The total number of frames
  50404. * @param from The frame at the beginning of the animation
  50405. * @param to The frame at the end of the animation
  50406. * @param loopMode Specifies the loop mode of the animation
  50407. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50408. * @param onAnimationEnd Callback to run once the animation is complete
  50409. * @returns Nullable animation
  50410. */
  50411. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50412. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50413. if (!animation) {
  50414. return null;
  50415. }
  50416. node.animations.push(animation);
  50417. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50418. };
  50419. /**
  50420. * Transition property of the Camera to the target Value
  50421. * @param property The property to transition
  50422. * @param targetValue The target Value of the property
  50423. * @param host The object where the property to animate belongs
  50424. * @param scene Scene used to run the animation
  50425. * @param frameRate Framerate (in frame/s) to use
  50426. * @param transition The transition type we want to use
  50427. * @param duration The duration of the animation, in milliseconds
  50428. * @param onAnimationEnd Callback trigger at the end of the animation
  50429. * @returns Nullable animation
  50430. */
  50431. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50432. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50433. if (duration <= 0) {
  50434. host[property] = targetValue;
  50435. if (onAnimationEnd) {
  50436. onAnimationEnd();
  50437. }
  50438. return null;
  50439. }
  50440. var endFrame = frameRate * (duration / 1000);
  50441. transition.setKeys([{
  50442. frame: 0,
  50443. value: host[property].clone ? host[property].clone() : host[property]
  50444. },
  50445. {
  50446. frame: endFrame,
  50447. value: targetValue
  50448. }]);
  50449. if (!host.animations) {
  50450. host.animations = [];
  50451. }
  50452. host.animations.push(transition);
  50453. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50454. animation.onAnimationEnd = onAnimationEnd;
  50455. return animation;
  50456. };
  50457. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50458. /**
  50459. * Return the array of runtime animations currently using this animation
  50460. */
  50461. get: function () {
  50462. return this._runtimeAnimations;
  50463. },
  50464. enumerable: true,
  50465. configurable: true
  50466. });
  50467. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50468. /**
  50469. * Specifies if any of the runtime animations are currently running
  50470. */
  50471. get: function () {
  50472. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50473. var runtimeAnimation = _a[_i];
  50474. if (!runtimeAnimation.isStopped) {
  50475. return true;
  50476. }
  50477. }
  50478. return false;
  50479. },
  50480. enumerable: true,
  50481. configurable: true
  50482. });
  50483. // Methods
  50484. /**
  50485. * Converts the animation to a string
  50486. * @param fullDetails support for multiple levels of logging within scene loading
  50487. * @returns String form of the animation
  50488. */
  50489. Animation.prototype.toString = function (fullDetails) {
  50490. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50491. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50492. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50493. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50494. if (fullDetails) {
  50495. ret += ", Ranges: {";
  50496. var first = true;
  50497. for (var name in this._ranges) {
  50498. if (first) {
  50499. ret += ", ";
  50500. first = false;
  50501. }
  50502. ret += name;
  50503. }
  50504. ret += "}";
  50505. }
  50506. return ret;
  50507. };
  50508. /**
  50509. * Add an event to this animation
  50510. * @param event Event to add
  50511. */
  50512. Animation.prototype.addEvent = function (event) {
  50513. this._events.push(event);
  50514. };
  50515. /**
  50516. * Remove all events found at the given frame
  50517. * @param frame The frame to remove events from
  50518. */
  50519. Animation.prototype.removeEvents = function (frame) {
  50520. for (var index = 0; index < this._events.length; index++) {
  50521. if (this._events[index].frame === frame) {
  50522. this._events.splice(index, 1);
  50523. index--;
  50524. }
  50525. }
  50526. };
  50527. /**
  50528. * Retrieves all the events from the animation
  50529. * @returns Events from the animation
  50530. */
  50531. Animation.prototype.getEvents = function () {
  50532. return this._events;
  50533. };
  50534. /**
  50535. * Creates an animation range
  50536. * @param name Name of the animation range
  50537. * @param from Starting frame of the animation range
  50538. * @param to Ending frame of the animation
  50539. */
  50540. Animation.prototype.createRange = function (name, from, to) {
  50541. // check name not already in use; could happen for bones after serialized
  50542. if (!this._ranges[name]) {
  50543. this._ranges[name] = new AnimationRange(name, from, to);
  50544. }
  50545. };
  50546. /**
  50547. * Deletes an animation range by name
  50548. * @param name Name of the animation range to delete
  50549. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50550. */
  50551. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50552. if (deleteFrames === void 0) { deleteFrames = true; }
  50553. var range = this._ranges[name];
  50554. if (!range) {
  50555. return;
  50556. }
  50557. if (deleteFrames) {
  50558. var from = range.from;
  50559. var to = range.to;
  50560. // this loop MUST go high to low for multiple splices to work
  50561. for (var key = this._keys.length - 1; key >= 0; key--) {
  50562. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50563. this._keys.splice(key, 1);
  50564. }
  50565. }
  50566. }
  50567. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50568. };
  50569. /**
  50570. * Gets the animation range by name, or null if not defined
  50571. * @param name Name of the animation range
  50572. * @returns Nullable animation range
  50573. */
  50574. Animation.prototype.getRange = function (name) {
  50575. return this._ranges[name];
  50576. };
  50577. /**
  50578. * Gets the key frames from the animation
  50579. * @returns The key frames of the animation
  50580. */
  50581. Animation.prototype.getKeys = function () {
  50582. return this._keys;
  50583. };
  50584. /**
  50585. * Gets the highest frame rate of the animation
  50586. * @returns Highest frame rate of the animation
  50587. */
  50588. Animation.prototype.getHighestFrame = function () {
  50589. var ret = 0;
  50590. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50591. if (ret < this._keys[key].frame) {
  50592. ret = this._keys[key].frame;
  50593. }
  50594. }
  50595. return ret;
  50596. };
  50597. /**
  50598. * Gets the easing function of the animation
  50599. * @returns Easing function of the animation
  50600. */
  50601. Animation.prototype.getEasingFunction = function () {
  50602. return this._easingFunction;
  50603. };
  50604. /**
  50605. * Sets the easing function of the animation
  50606. * @param easingFunction A custom mathematical formula for animation
  50607. */
  50608. Animation.prototype.setEasingFunction = function (easingFunction) {
  50609. this._easingFunction = easingFunction;
  50610. };
  50611. /**
  50612. * Interpolates a scalar linearly
  50613. * @param startValue Start value of the animation curve
  50614. * @param endValue End value of the animation curve
  50615. * @param gradient Scalar amount to interpolate
  50616. * @returns Interpolated scalar value
  50617. */
  50618. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50619. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50620. };
  50621. /**
  50622. * Interpolates a scalar cubically
  50623. * @param startValue Start value of the animation curve
  50624. * @param outTangent End tangent of the animation
  50625. * @param endValue End value of the animation curve
  50626. * @param inTangent Start tangent of the animation curve
  50627. * @param gradient Scalar amount to interpolate
  50628. * @returns Interpolated scalar value
  50629. */
  50630. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50631. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50632. };
  50633. /**
  50634. * Interpolates a quaternion using a spherical linear interpolation
  50635. * @param startValue Start value of the animation curve
  50636. * @param endValue End value of the animation curve
  50637. * @param gradient Scalar amount to interpolate
  50638. * @returns Interpolated quaternion value
  50639. */
  50640. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50641. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50642. };
  50643. /**
  50644. * Interpolates a quaternion cubically
  50645. * @param startValue Start value of the animation curve
  50646. * @param outTangent End tangent of the animation curve
  50647. * @param endValue End value of the animation curve
  50648. * @param inTangent Start tangent of the animation curve
  50649. * @param gradient Scalar amount to interpolate
  50650. * @returns Interpolated quaternion value
  50651. */
  50652. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50653. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50654. };
  50655. /**
  50656. * Interpolates a Vector3 linearl
  50657. * @param startValue Start value of the animation curve
  50658. * @param endValue End value of the animation curve
  50659. * @param gradient Scalar amount to interpolate
  50660. * @returns Interpolated scalar value
  50661. */
  50662. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50663. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50664. };
  50665. /**
  50666. * Interpolates a Vector3 cubically
  50667. * @param startValue Start value of the animation curve
  50668. * @param outTangent End tangent of the animation
  50669. * @param endValue End value of the animation curve
  50670. * @param inTangent Start tangent of the animation curve
  50671. * @param gradient Scalar amount to interpolate
  50672. * @returns InterpolatedVector3 value
  50673. */
  50674. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50675. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50676. };
  50677. /**
  50678. * Interpolates a Vector2 linearly
  50679. * @param startValue Start value of the animation curve
  50680. * @param endValue End value of the animation curve
  50681. * @param gradient Scalar amount to interpolate
  50682. * @returns Interpolated Vector2 value
  50683. */
  50684. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50685. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50686. };
  50687. /**
  50688. * Interpolates a Vector2 cubically
  50689. * @param startValue Start value of the animation curve
  50690. * @param outTangent End tangent of the animation
  50691. * @param endValue End value of the animation curve
  50692. * @param inTangent Start tangent of the animation curve
  50693. * @param gradient Scalar amount to interpolate
  50694. * @returns Interpolated Vector2 value
  50695. */
  50696. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50697. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50698. };
  50699. /**
  50700. * Interpolates a size linearly
  50701. * @param startValue Start value of the animation curve
  50702. * @param endValue End value of the animation curve
  50703. * @param gradient Scalar amount to interpolate
  50704. * @returns Interpolated Size value
  50705. */
  50706. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50707. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50708. };
  50709. /**
  50710. * Interpolates a Color3 linearly
  50711. * @param startValue Start value of the animation curve
  50712. * @param endValue End value of the animation curve
  50713. * @param gradient Scalar amount to interpolate
  50714. * @returns Interpolated Color3 value
  50715. */
  50716. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50717. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50718. };
  50719. /**
  50720. * @hidden Internal use only
  50721. */
  50722. Animation.prototype._getKeyValue = function (value) {
  50723. if (typeof value === "function") {
  50724. return value();
  50725. }
  50726. return value;
  50727. };
  50728. /**
  50729. * @hidden Internal use only
  50730. */
  50731. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50732. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50733. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50734. }
  50735. var keys = this.getKeys();
  50736. // Try to get a hash to find the right key
  50737. 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));
  50738. if (keys[startKeyIndex].frame >= currentFrame) {
  50739. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50740. startKeyIndex--;
  50741. }
  50742. }
  50743. for (var key = startKeyIndex; key < keys.length; key++) {
  50744. var endKey = keys[key + 1];
  50745. if (endKey.frame >= currentFrame) {
  50746. var startKey = keys[key];
  50747. var startValue = this._getKeyValue(startKey.value);
  50748. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50749. return startValue;
  50750. }
  50751. var endValue = this._getKeyValue(endKey.value);
  50752. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50753. var frameDelta = endKey.frame - startKey.frame;
  50754. // gradient : percent of currentFrame between the frame inf and the frame sup
  50755. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50756. // check for easingFunction and correction of gradient
  50757. var easingFunction = this.getEasingFunction();
  50758. if (easingFunction != null) {
  50759. gradient = easingFunction.ease(gradient);
  50760. }
  50761. switch (this.dataType) {
  50762. // Float
  50763. case Animation.ANIMATIONTYPE_FLOAT:
  50764. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50765. switch (loopMode) {
  50766. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50767. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50768. return floatValue;
  50769. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50770. return offsetValue * repeatCount + floatValue;
  50771. }
  50772. break;
  50773. // Quaternion
  50774. case Animation.ANIMATIONTYPE_QUATERNION:
  50775. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50776. switch (loopMode) {
  50777. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50778. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50779. return quatValue;
  50780. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50781. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50782. }
  50783. return quatValue;
  50784. // Vector3
  50785. case Animation.ANIMATIONTYPE_VECTOR3:
  50786. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50787. switch (loopMode) {
  50788. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50789. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50790. return vec3Value;
  50791. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50792. return vec3Value.add(offsetValue.scale(repeatCount));
  50793. }
  50794. // Vector2
  50795. case Animation.ANIMATIONTYPE_VECTOR2:
  50796. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50797. switch (loopMode) {
  50798. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50799. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50800. return vec2Value;
  50801. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50802. return vec2Value.add(offsetValue.scale(repeatCount));
  50803. }
  50804. // Size
  50805. case Animation.ANIMATIONTYPE_SIZE:
  50806. switch (loopMode) {
  50807. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50808. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50809. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50810. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50811. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50812. }
  50813. // Color3
  50814. case Animation.ANIMATIONTYPE_COLOR3:
  50815. switch (loopMode) {
  50816. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50817. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50818. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50819. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50820. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50821. }
  50822. // Matrix
  50823. case Animation.ANIMATIONTYPE_MATRIX:
  50824. switch (loopMode) {
  50825. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50826. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50827. if (Animation.AllowMatricesInterpolation) {
  50828. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50829. }
  50830. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50831. return startValue;
  50832. }
  50833. default:
  50834. break;
  50835. }
  50836. break;
  50837. }
  50838. }
  50839. return this._getKeyValue(keys[keys.length - 1].value);
  50840. };
  50841. /**
  50842. * Defines the function to use to interpolate matrices
  50843. * @param startValue defines the start matrix
  50844. * @param endValue defines the end matrix
  50845. * @param gradient defines the gradient between both matrices
  50846. * @param result defines an optional target matrix where to store the interpolation
  50847. * @returns the interpolated matrix
  50848. */
  50849. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50850. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50851. if (result) {
  50852. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50853. return result;
  50854. }
  50855. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50856. }
  50857. if (result) {
  50858. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50859. return result;
  50860. }
  50861. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50862. };
  50863. /**
  50864. * Makes a copy of the animation
  50865. * @returns Cloned animation
  50866. */
  50867. Animation.prototype.clone = function () {
  50868. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50869. clone.enableBlending = this.enableBlending;
  50870. clone.blendingSpeed = this.blendingSpeed;
  50871. if (this._keys) {
  50872. clone.setKeys(this._keys);
  50873. }
  50874. if (this._ranges) {
  50875. clone._ranges = {};
  50876. for (var name in this._ranges) {
  50877. var range = this._ranges[name];
  50878. if (!range) {
  50879. continue;
  50880. }
  50881. clone._ranges[name] = range.clone();
  50882. }
  50883. }
  50884. return clone;
  50885. };
  50886. /**
  50887. * Sets the key frames of the animation
  50888. * @param values The animation key frames to set
  50889. */
  50890. Animation.prototype.setKeys = function (values) {
  50891. this._keys = values.slice(0);
  50892. };
  50893. /**
  50894. * Serializes the animation to an object
  50895. * @returns Serialized object
  50896. */
  50897. Animation.prototype.serialize = function () {
  50898. var serializationObject = {};
  50899. serializationObject.name = this.name;
  50900. serializationObject.property = this.targetProperty;
  50901. serializationObject.framePerSecond = this.framePerSecond;
  50902. serializationObject.dataType = this.dataType;
  50903. serializationObject.loopBehavior = this.loopMode;
  50904. serializationObject.enableBlending = this.enableBlending;
  50905. serializationObject.blendingSpeed = this.blendingSpeed;
  50906. var dataType = this.dataType;
  50907. serializationObject.keys = [];
  50908. var keys = this.getKeys();
  50909. for (var index = 0; index < keys.length; index++) {
  50910. var animationKey = keys[index];
  50911. var key = {};
  50912. key.frame = animationKey.frame;
  50913. switch (dataType) {
  50914. case Animation.ANIMATIONTYPE_FLOAT:
  50915. key.values = [animationKey.value];
  50916. break;
  50917. case Animation.ANIMATIONTYPE_QUATERNION:
  50918. case Animation.ANIMATIONTYPE_MATRIX:
  50919. case Animation.ANIMATIONTYPE_VECTOR3:
  50920. case Animation.ANIMATIONTYPE_COLOR3:
  50921. key.values = animationKey.value.asArray();
  50922. break;
  50923. }
  50924. serializationObject.keys.push(key);
  50925. }
  50926. serializationObject.ranges = [];
  50927. for (var name in this._ranges) {
  50928. var source = this._ranges[name];
  50929. if (!source) {
  50930. continue;
  50931. }
  50932. var range = {};
  50933. range.name = name;
  50934. range.from = source.from;
  50935. range.to = source.to;
  50936. serializationObject.ranges.push(range);
  50937. }
  50938. return serializationObject;
  50939. };
  50940. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50941. /**
  50942. * Get the float animation type
  50943. */
  50944. get: function () {
  50945. return Animation._ANIMATIONTYPE_FLOAT;
  50946. },
  50947. enumerable: true,
  50948. configurable: true
  50949. });
  50950. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50951. /**
  50952. * Get the Vector3 animation type
  50953. */
  50954. get: function () {
  50955. return Animation._ANIMATIONTYPE_VECTOR3;
  50956. },
  50957. enumerable: true,
  50958. configurable: true
  50959. });
  50960. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50961. /**
  50962. * Get the Vectpr2 animation type
  50963. */
  50964. get: function () {
  50965. return Animation._ANIMATIONTYPE_VECTOR2;
  50966. },
  50967. enumerable: true,
  50968. configurable: true
  50969. });
  50970. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50971. /**
  50972. * Get the Size animation type
  50973. */
  50974. get: function () {
  50975. return Animation._ANIMATIONTYPE_SIZE;
  50976. },
  50977. enumerable: true,
  50978. configurable: true
  50979. });
  50980. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50981. /**
  50982. * Get the Quaternion animation type
  50983. */
  50984. get: function () {
  50985. return Animation._ANIMATIONTYPE_QUATERNION;
  50986. },
  50987. enumerable: true,
  50988. configurable: true
  50989. });
  50990. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50991. /**
  50992. * Get the Matrix animation type
  50993. */
  50994. get: function () {
  50995. return Animation._ANIMATIONTYPE_MATRIX;
  50996. },
  50997. enumerable: true,
  50998. configurable: true
  50999. });
  51000. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51001. /**
  51002. * Get the Color3 animation type
  51003. */
  51004. get: function () {
  51005. return Animation._ANIMATIONTYPE_COLOR3;
  51006. },
  51007. enumerable: true,
  51008. configurable: true
  51009. });
  51010. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51011. /**
  51012. * Get the Relative Loop Mode
  51013. */
  51014. get: function () {
  51015. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51016. },
  51017. enumerable: true,
  51018. configurable: true
  51019. });
  51020. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51021. /**
  51022. * Get the Cycle Loop Mode
  51023. */
  51024. get: function () {
  51025. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51026. },
  51027. enumerable: true,
  51028. configurable: true
  51029. });
  51030. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51031. /**
  51032. * Get the Constant Loop Mode
  51033. */
  51034. get: function () {
  51035. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51036. },
  51037. enumerable: true,
  51038. configurable: true
  51039. });
  51040. /** @hidden */
  51041. Animation._UniversalLerp = function (left, right, amount) {
  51042. var constructor = left.constructor;
  51043. if (constructor.Lerp) { // Lerp supported
  51044. return constructor.Lerp(left, right, amount);
  51045. }
  51046. else if (constructor.Slerp) { // Slerp supported
  51047. return constructor.Slerp(left, right, amount);
  51048. }
  51049. else if (left.toFixed) { // Number
  51050. return left * (1.0 - amount) + amount * right;
  51051. }
  51052. else { // Blending not supported
  51053. return right;
  51054. }
  51055. };
  51056. /**
  51057. * Parses an animation object and creates an animation
  51058. * @param parsedAnimation Parsed animation object
  51059. * @returns Animation object
  51060. */
  51061. Animation.Parse = function (parsedAnimation) {
  51062. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51063. var dataType = parsedAnimation.dataType;
  51064. var keys = [];
  51065. var data;
  51066. var index;
  51067. if (parsedAnimation.enableBlending) {
  51068. animation.enableBlending = parsedAnimation.enableBlending;
  51069. }
  51070. if (parsedAnimation.blendingSpeed) {
  51071. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51072. }
  51073. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51074. var key = parsedAnimation.keys[index];
  51075. var inTangent;
  51076. var outTangent;
  51077. switch (dataType) {
  51078. case Animation.ANIMATIONTYPE_FLOAT:
  51079. data = key.values[0];
  51080. if (key.values.length >= 1) {
  51081. inTangent = key.values[1];
  51082. }
  51083. if (key.values.length >= 2) {
  51084. outTangent = key.values[2];
  51085. }
  51086. break;
  51087. case Animation.ANIMATIONTYPE_QUATERNION:
  51088. data = BABYLON.Quaternion.FromArray(key.values);
  51089. if (key.values.length >= 8) {
  51090. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51091. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51092. inTangent = _inTangent;
  51093. }
  51094. }
  51095. if (key.values.length >= 12) {
  51096. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51097. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51098. outTangent = _outTangent;
  51099. }
  51100. }
  51101. break;
  51102. case Animation.ANIMATIONTYPE_MATRIX:
  51103. data = BABYLON.Matrix.FromArray(key.values);
  51104. break;
  51105. case Animation.ANIMATIONTYPE_COLOR3:
  51106. data = BABYLON.Color3.FromArray(key.values);
  51107. break;
  51108. case Animation.ANIMATIONTYPE_VECTOR3:
  51109. default:
  51110. data = BABYLON.Vector3.FromArray(key.values);
  51111. break;
  51112. }
  51113. var keyData = {};
  51114. keyData.frame = key.frame;
  51115. keyData.value = data;
  51116. if (inTangent != undefined) {
  51117. keyData.inTangent = inTangent;
  51118. }
  51119. if (outTangent != undefined) {
  51120. keyData.outTangent = outTangent;
  51121. }
  51122. keys.push(keyData);
  51123. }
  51124. animation.setKeys(keys);
  51125. if (parsedAnimation.ranges) {
  51126. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51127. data = parsedAnimation.ranges[index];
  51128. animation.createRange(data.name, data.from, data.to);
  51129. }
  51130. }
  51131. return animation;
  51132. };
  51133. /**
  51134. * Appends the serialized animations from the source animations
  51135. * @param source Source containing the animations
  51136. * @param destination Target to store the animations
  51137. */
  51138. Animation.AppendSerializedAnimations = function (source, destination) {
  51139. if (source.animations) {
  51140. destination.animations = [];
  51141. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51142. var animation = source.animations[animationIndex];
  51143. destination.animations.push(animation.serialize());
  51144. }
  51145. }
  51146. };
  51147. /**
  51148. * Use matrix interpolation instead of using direct key value when animating matrices
  51149. */
  51150. Animation.AllowMatricesInterpolation = false;
  51151. /**
  51152. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51153. */
  51154. Animation.AllowMatrixDecomposeForInterpolation = true;
  51155. // Statics
  51156. /**
  51157. * Float animation type
  51158. */
  51159. Animation._ANIMATIONTYPE_FLOAT = 0;
  51160. /**
  51161. * Vector3 animation type
  51162. */
  51163. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51164. /**
  51165. * Quaternion animation type
  51166. */
  51167. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51168. /**
  51169. * Matrix animation type
  51170. */
  51171. Animation._ANIMATIONTYPE_MATRIX = 3;
  51172. /**
  51173. * Color3 animation type
  51174. */
  51175. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51176. /**
  51177. * Vector2 animation type
  51178. */
  51179. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51180. /**
  51181. * Size animation type
  51182. */
  51183. Animation._ANIMATIONTYPE_SIZE = 6;
  51184. /**
  51185. * Relative Loop Mode
  51186. */
  51187. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51188. /**
  51189. * Cycle Loop Mode
  51190. */
  51191. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51192. /**
  51193. * Constant Loop Mode
  51194. */
  51195. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51196. return Animation;
  51197. }());
  51198. BABYLON.Animation = Animation;
  51199. })(BABYLON || (BABYLON = {}));
  51200. //# sourceMappingURL=babylon.animation.js.map
  51201. var BABYLON;
  51202. (function (BABYLON) {
  51203. /**
  51204. * This class defines the direct association between an animation and a target
  51205. */
  51206. var TargetedAnimation = /** @class */ (function () {
  51207. function TargetedAnimation() {
  51208. }
  51209. return TargetedAnimation;
  51210. }());
  51211. BABYLON.TargetedAnimation = TargetedAnimation;
  51212. /**
  51213. * Use this class to create coordinated animations on multiple targets
  51214. */
  51215. var AnimationGroup = /** @class */ (function () {
  51216. function AnimationGroup(name, scene) {
  51217. if (scene === void 0) { scene = null; }
  51218. this.name = name;
  51219. this._targetedAnimations = new Array();
  51220. this._animatables = new Array();
  51221. this._from = Number.MAX_VALUE;
  51222. this._to = -Number.MAX_VALUE;
  51223. this._speedRatio = 1;
  51224. this.onAnimationEndObservable = new BABYLON.Observable();
  51225. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51226. this._scene.animationGroups.push(this);
  51227. }
  51228. Object.defineProperty(AnimationGroup.prototype, "from", {
  51229. /**
  51230. * Gets the first frame
  51231. */
  51232. get: function () {
  51233. return this._from;
  51234. },
  51235. enumerable: true,
  51236. configurable: true
  51237. });
  51238. Object.defineProperty(AnimationGroup.prototype, "to", {
  51239. /**
  51240. * Gets the last frame
  51241. */
  51242. get: function () {
  51243. return this._to;
  51244. },
  51245. enumerable: true,
  51246. configurable: true
  51247. });
  51248. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51249. /**
  51250. * Define if the animations are started
  51251. */
  51252. get: function () {
  51253. return this._isStarted;
  51254. },
  51255. enumerable: true,
  51256. configurable: true
  51257. });
  51258. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51259. /**
  51260. * Gets or sets the speed ratio to use for all animations
  51261. */
  51262. get: function () {
  51263. return this._speedRatio;
  51264. },
  51265. /**
  51266. * Gets or sets the speed ratio to use for all animations
  51267. */
  51268. set: function (value) {
  51269. if (this._speedRatio === value) {
  51270. return;
  51271. }
  51272. this._speedRatio = value;
  51273. for (var index = 0; index < this._animatables.length; index++) {
  51274. var animatable = this._animatables[index];
  51275. animatable.speedRatio = this._speedRatio;
  51276. }
  51277. },
  51278. enumerable: true,
  51279. configurable: true
  51280. });
  51281. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51282. /**
  51283. * Gets the targeted animations for this animation group
  51284. */
  51285. get: function () {
  51286. return this._targetedAnimations;
  51287. },
  51288. enumerable: true,
  51289. configurable: true
  51290. });
  51291. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51292. /**
  51293. * returning the list of animatables controlled by this animation group.
  51294. */
  51295. get: function () {
  51296. return this._animatables;
  51297. },
  51298. enumerable: true,
  51299. configurable: true
  51300. });
  51301. /**
  51302. * Add an animation (with its target) in the group
  51303. * @param animation defines the animation we want to add
  51304. * @param target defines the target of the animation
  51305. * @returns the {BABYLON.TargetedAnimation} object
  51306. */
  51307. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51308. var targetedAnimation = {
  51309. animation: animation,
  51310. target: target
  51311. };
  51312. var keys = animation.getKeys();
  51313. if (this._from > keys[0].frame) {
  51314. this._from = keys[0].frame;
  51315. }
  51316. if (this._to < keys[keys.length - 1].frame) {
  51317. this._to = keys[keys.length - 1].frame;
  51318. }
  51319. this._targetedAnimations.push(targetedAnimation);
  51320. return targetedAnimation;
  51321. };
  51322. /**
  51323. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51324. * It can add constant keys at begin or end
  51325. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51326. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51327. */
  51328. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51329. if (beginFrame === void 0) { beginFrame = null; }
  51330. if (endFrame === void 0) { endFrame = null; }
  51331. if (beginFrame == null)
  51332. beginFrame = this._from;
  51333. if (endFrame == null)
  51334. endFrame = this._to;
  51335. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51336. var targetedAnimation = this._targetedAnimations[index];
  51337. var keys = targetedAnimation.animation.getKeys();
  51338. var startKey = keys[0];
  51339. var endKey = keys[keys.length - 1];
  51340. if (startKey.frame > beginFrame) {
  51341. var newKey = {
  51342. frame: beginFrame,
  51343. value: startKey.value,
  51344. inTangent: startKey.inTangent,
  51345. outTangent: startKey.outTangent,
  51346. interpolation: startKey.interpolation
  51347. };
  51348. keys.splice(0, 0, newKey);
  51349. }
  51350. if (endKey.frame < endFrame) {
  51351. var newKey = {
  51352. frame: endFrame,
  51353. value: endKey.value,
  51354. inTangent: endKey.outTangent,
  51355. outTangent: endKey.outTangent,
  51356. interpolation: endKey.interpolation
  51357. };
  51358. keys.push(newKey);
  51359. }
  51360. }
  51361. this._from = beginFrame;
  51362. this._to = endFrame;
  51363. return this;
  51364. };
  51365. /**
  51366. * Start all animations on given targets
  51367. * @param loop defines if animations must loop
  51368. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51369. * @param from defines the from key (optional)
  51370. * @param to defines the to key (optional)
  51371. * @returns the current animation group
  51372. */
  51373. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51374. var _this = this;
  51375. if (loop === void 0) { loop = false; }
  51376. if (speedRatio === void 0) { speedRatio = 1; }
  51377. if (this._isStarted || this._targetedAnimations.length === 0) {
  51378. return this;
  51379. }
  51380. var _loop_1 = function (targetedAnimation) {
  51381. 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 () {
  51382. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51383. }));
  51384. };
  51385. var this_1 = this;
  51386. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51387. var targetedAnimation = _a[_i];
  51388. _loop_1(targetedAnimation);
  51389. }
  51390. this._speedRatio = speedRatio;
  51391. this._isStarted = true;
  51392. return this;
  51393. };
  51394. /**
  51395. * Pause all animations
  51396. */
  51397. AnimationGroup.prototype.pause = function () {
  51398. if (!this._isStarted) {
  51399. return this;
  51400. }
  51401. for (var index = 0; index < this._animatables.length; index++) {
  51402. var animatable = this._animatables[index];
  51403. animatable.pause();
  51404. }
  51405. return this;
  51406. };
  51407. /**
  51408. * Play all animations to initial state
  51409. * This function will start() the animations if they were not started or will restart() them if they were paused
  51410. * @param loop defines if animations must loop
  51411. */
  51412. AnimationGroup.prototype.play = function (loop) {
  51413. if (this.isStarted) {
  51414. if (loop !== undefined) {
  51415. for (var index = 0; index < this._animatables.length; index++) {
  51416. var animatable = this._animatables[index];
  51417. animatable.loopAnimation = loop;
  51418. }
  51419. }
  51420. this.restart();
  51421. }
  51422. else {
  51423. this.start(loop, this._speedRatio);
  51424. }
  51425. return this;
  51426. };
  51427. /**
  51428. * Reset all animations to initial state
  51429. */
  51430. AnimationGroup.prototype.reset = function () {
  51431. if (!this._isStarted) {
  51432. return this;
  51433. }
  51434. for (var index = 0; index < this._animatables.length; index++) {
  51435. var animatable = this._animatables[index];
  51436. animatable.reset();
  51437. }
  51438. return this;
  51439. };
  51440. /**
  51441. * Restart animations from key 0
  51442. */
  51443. AnimationGroup.prototype.restart = function () {
  51444. if (!this._isStarted) {
  51445. return this;
  51446. }
  51447. for (var index = 0; index < this._animatables.length; index++) {
  51448. var animatable = this._animatables[index];
  51449. animatable.restart();
  51450. }
  51451. return this;
  51452. };
  51453. /**
  51454. * Stop all animations
  51455. */
  51456. AnimationGroup.prototype.stop = function () {
  51457. if (!this._isStarted) {
  51458. return this;
  51459. }
  51460. for (var index = 0; index < this._animatables.length; index++) {
  51461. var animatable = this._animatables[index];
  51462. animatable.stop();
  51463. }
  51464. this._isStarted = false;
  51465. return this;
  51466. };
  51467. /**
  51468. * Set animation weight for all animatables
  51469. * @param weight defines the weight to use
  51470. * @return the animationGroup
  51471. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51472. */
  51473. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51474. for (var index = 0; index < this._animatables.length; index++) {
  51475. var animatable = this._animatables[index];
  51476. animatable.weight = weight;
  51477. }
  51478. return this;
  51479. };
  51480. /**
  51481. * Synchronize and normalize all animatables with a source animatable
  51482. * @param root defines the root animatable to synchronize with
  51483. * @return the animationGroup
  51484. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51485. */
  51486. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51487. for (var index = 0; index < this._animatables.length; index++) {
  51488. var animatable = this._animatables[index];
  51489. animatable.syncWith(root);
  51490. }
  51491. return this;
  51492. };
  51493. /**
  51494. * Goes to a specific frame in this animation group
  51495. * @param frame the frame number to go to
  51496. * @return the animationGroup
  51497. */
  51498. AnimationGroup.prototype.goToFrame = function (frame) {
  51499. if (!this._isStarted) {
  51500. return this;
  51501. }
  51502. for (var index = 0; index < this._animatables.length; index++) {
  51503. var animatable = this._animatables[index];
  51504. animatable.goToFrame(frame);
  51505. }
  51506. return this;
  51507. };
  51508. /**
  51509. * Dispose all associated resources
  51510. */
  51511. AnimationGroup.prototype.dispose = function () {
  51512. this._targetedAnimations = [];
  51513. this._animatables = [];
  51514. var index = this._scene.animationGroups.indexOf(this);
  51515. if (index > -1) {
  51516. this._scene.animationGroups.splice(index, 1);
  51517. }
  51518. };
  51519. return AnimationGroup;
  51520. }());
  51521. BABYLON.AnimationGroup = AnimationGroup;
  51522. })(BABYLON || (BABYLON = {}));
  51523. //# sourceMappingURL=babylon.animationGroup.js.map
  51524. var BABYLON;
  51525. (function (BABYLON) {
  51526. /**
  51527. * Defines a runtime animation
  51528. */
  51529. var RuntimeAnimation = /** @class */ (function () {
  51530. /**
  51531. * Create a new RuntimeAnimation object
  51532. * @param target defines the target of the animation
  51533. * @param animation defines the source animation object
  51534. * @param scene defines the hosting scene
  51535. * @param host defines the initiating Animatable
  51536. */
  51537. function RuntimeAnimation(target, animation, scene, host) {
  51538. /**
  51539. * The current frame of the runtime animation
  51540. */
  51541. this._currentFrame = 0;
  51542. /**
  51543. * The original value of the runtime animation
  51544. */
  51545. this._originalValue = new Array();
  51546. /**
  51547. * The offsets cache of the runtime animation
  51548. */
  51549. this._offsetsCache = {};
  51550. /**
  51551. * The high limits cache of the runtime animation
  51552. */
  51553. this._highLimitsCache = {};
  51554. /**
  51555. * Specifies if the runtime animation has been stopped
  51556. */
  51557. this._stopped = false;
  51558. /**
  51559. * The blending factor of the runtime animation
  51560. */
  51561. this._blendingFactor = 0;
  51562. /**
  51563. * The target path of the runtime animation
  51564. */
  51565. this._targetPath = "";
  51566. /**
  51567. * The weight of the runtime animation
  51568. */
  51569. this._weight = 1.0;
  51570. /**
  51571. * The ratio offset of the runtime animation
  51572. */
  51573. this._ratioOffset = 0;
  51574. /**
  51575. * The previous delay of the runtime animation
  51576. */
  51577. this._previousDelay = 0;
  51578. /**
  51579. * The previous ratio of the runtime animation
  51580. */
  51581. this._previousRatio = 0;
  51582. this._animation = animation;
  51583. this._target = target;
  51584. this._scene = scene;
  51585. this._host = host;
  51586. animation._runtimeAnimations.push(this);
  51587. }
  51588. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51589. /**
  51590. * Gets the current frame of the runtime animation
  51591. */
  51592. get: function () {
  51593. return this._currentFrame;
  51594. },
  51595. enumerable: true,
  51596. configurable: true
  51597. });
  51598. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51599. /**
  51600. * Gets the weight of the runtime animation
  51601. */
  51602. get: function () {
  51603. return this._weight;
  51604. },
  51605. enumerable: true,
  51606. configurable: true
  51607. });
  51608. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51609. /**
  51610. * Gets the current value of the runtime animation
  51611. */
  51612. get: function () {
  51613. return this._currentValue;
  51614. },
  51615. enumerable: true,
  51616. configurable: true
  51617. });
  51618. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51619. /**
  51620. * Gets the target path of the runtime animation
  51621. */
  51622. get: function () {
  51623. return this._targetPath;
  51624. },
  51625. enumerable: true,
  51626. configurable: true
  51627. });
  51628. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51629. /**
  51630. * Gets the actual target of the runtime animation
  51631. */
  51632. get: function () {
  51633. return this._activeTarget;
  51634. },
  51635. enumerable: true,
  51636. configurable: true
  51637. });
  51638. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51639. /**
  51640. * Gets the animation from the runtime animation
  51641. */
  51642. get: function () {
  51643. return this._animation;
  51644. },
  51645. enumerable: true,
  51646. configurable: true
  51647. });
  51648. /**
  51649. * Resets the runtime animation to the beginning
  51650. * @param restoreOriginal defines whether to restore the target property to the original value
  51651. */
  51652. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51653. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51654. if (restoreOriginal) {
  51655. if (this._target instanceof Array) {
  51656. var index = 0;
  51657. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51658. var target = _a[_i];
  51659. if (this._originalValue[index] !== undefined) {
  51660. this._setValue(target, this._originalValue[index], -1);
  51661. }
  51662. index++;
  51663. }
  51664. }
  51665. else {
  51666. if (this._originalValue[0] !== undefined) {
  51667. this._setValue(this._target, this._originalValue[0], -1);
  51668. }
  51669. }
  51670. }
  51671. this._offsetsCache = {};
  51672. this._highLimitsCache = {};
  51673. this._currentFrame = 0;
  51674. this._blendingFactor = 0;
  51675. this._originalValue = new Array();
  51676. };
  51677. /**
  51678. * Specifies if the runtime animation is stopped
  51679. * @returns Boolean specifying if the runtime animation is stopped
  51680. */
  51681. RuntimeAnimation.prototype.isStopped = function () {
  51682. return this._stopped;
  51683. };
  51684. /**
  51685. * Disposes of the runtime animation
  51686. */
  51687. RuntimeAnimation.prototype.dispose = function () {
  51688. var index = this._animation.runtimeAnimations.indexOf(this);
  51689. if (index > -1) {
  51690. this._animation.runtimeAnimations.splice(index, 1);
  51691. }
  51692. };
  51693. /**
  51694. * Interpolates the animation from the current frame
  51695. * @param currentFrame The frame to interpolate the animation to
  51696. * @param repeatCount The number of times that the animation should loop
  51697. * @param loopMode The type of looping mode to use
  51698. * @param offsetValue Animation offset value
  51699. * @param highLimitValue The high limit value
  51700. * @returns The interpolated value
  51701. */
  51702. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51703. this._currentFrame = currentFrame;
  51704. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51705. this._workValue = BABYLON.Matrix.Zero();
  51706. }
  51707. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51708. };
  51709. /**
  51710. * Apply the interpolated value to the target
  51711. * @param currentValue defines the value computed by the animation
  51712. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51713. */
  51714. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51715. if (weight === void 0) { weight = 1.0; }
  51716. if (this._target instanceof Array) {
  51717. var index = 0;
  51718. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51719. var target = _a[_i];
  51720. this._setValue(target, currentValue, weight, index);
  51721. index++;
  51722. }
  51723. }
  51724. else {
  51725. this._setValue(this._target, currentValue, weight);
  51726. }
  51727. };
  51728. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51729. if (targetIndex === void 0) { targetIndex = 0; }
  51730. // Set value
  51731. var path;
  51732. var destination;
  51733. var targetPropertyPath = this._animation.targetPropertyPath;
  51734. if (targetPropertyPath.length > 1) {
  51735. var property = target[targetPropertyPath[0]];
  51736. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51737. property = property[targetPropertyPath[index]];
  51738. }
  51739. path = targetPropertyPath[targetPropertyPath.length - 1];
  51740. destination = property;
  51741. }
  51742. else {
  51743. path = targetPropertyPath[0];
  51744. destination = target;
  51745. }
  51746. this._targetPath = path;
  51747. this._activeTarget = destination;
  51748. this._weight = weight;
  51749. if (this._originalValue[targetIndex] === undefined) {
  51750. var originalValue = void 0;
  51751. if (destination.getRestPose && path === "_matrix") { // For bones
  51752. originalValue = destination.getRestPose();
  51753. }
  51754. else {
  51755. originalValue = destination[path];
  51756. }
  51757. if (originalValue && originalValue.clone) {
  51758. this._originalValue[targetIndex] = originalValue.clone();
  51759. }
  51760. else {
  51761. this._originalValue[targetIndex] = originalValue;
  51762. }
  51763. }
  51764. // Blending
  51765. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51766. if (enableBlending && this._blendingFactor <= 1.0) {
  51767. if (!this._originalBlendValue) {
  51768. var originalValue = destination[path];
  51769. if (originalValue.clone) {
  51770. this._originalBlendValue = originalValue.clone();
  51771. }
  51772. else {
  51773. this._originalBlendValue = originalValue;
  51774. }
  51775. }
  51776. if (this._originalBlendValue.m) { // Matrix
  51777. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51778. if (this._currentValue) {
  51779. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51780. }
  51781. else {
  51782. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51783. }
  51784. }
  51785. else {
  51786. if (this._currentValue) {
  51787. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51788. }
  51789. else {
  51790. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51791. }
  51792. }
  51793. }
  51794. else {
  51795. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51796. }
  51797. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51798. this._blendingFactor += blendingSpeed;
  51799. }
  51800. else {
  51801. this._currentValue = currentValue;
  51802. }
  51803. if (weight !== -1.0) {
  51804. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51805. }
  51806. else {
  51807. destination[path] = this._currentValue;
  51808. }
  51809. if (target.markAsDirty) {
  51810. target.markAsDirty(this._animation.targetProperty);
  51811. }
  51812. };
  51813. /**
  51814. * Gets the loop pmode of the runtime animation
  51815. * @returns Loop Mode
  51816. */
  51817. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51818. if (this._target && this._target.animationPropertiesOverride) {
  51819. return this._target.animationPropertiesOverride.loopMode;
  51820. }
  51821. return this._animation.loopMode;
  51822. };
  51823. /**
  51824. * Move the current animation to a given frame
  51825. * @param frame defines the frame to move to
  51826. */
  51827. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51828. var keys = this._animation.getKeys();
  51829. if (frame < keys[0].frame) {
  51830. frame = keys[0].frame;
  51831. }
  51832. else if (frame > keys[keys.length - 1].frame) {
  51833. frame = keys[keys.length - 1].frame;
  51834. }
  51835. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51836. this.setValue(currentValue, -1);
  51837. };
  51838. /**
  51839. * @hidden Internal use only
  51840. */
  51841. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51842. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51843. this._ratioOffset = this._previousRatio - newRatio;
  51844. };
  51845. /**
  51846. * Execute the current animation
  51847. * @param delay defines the delay to add to the current frame
  51848. * @param from defines the lower bound of the animation range
  51849. * @param to defines the upper bound of the animation range
  51850. * @param loop defines if the current animation must loop
  51851. * @param speedRatio defines the current speed ratio
  51852. * @param weight defines the weight of the animation (default is -1 so no weight)
  51853. * @returns a boolean indicating if the animation has ended
  51854. */
  51855. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51856. if (weight === void 0) { weight = -1.0; }
  51857. var targetPropertyPath = this._animation.targetPropertyPath;
  51858. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51859. this._stopped = true;
  51860. return false;
  51861. }
  51862. var returnValue = true;
  51863. var keys = this._animation.getKeys();
  51864. // Adding a start key at frame 0 if missing
  51865. if (keys[0].frame !== 0) {
  51866. var newKey = { frame: 0, value: keys[0].value };
  51867. keys.splice(0, 0, newKey);
  51868. }
  51869. // Check limits
  51870. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51871. from = keys[0].frame;
  51872. }
  51873. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51874. to = keys[keys.length - 1].frame;
  51875. }
  51876. //to and from cannot be the same key
  51877. if (from === to) {
  51878. if (from > keys[0].frame) {
  51879. from--;
  51880. }
  51881. else if (to < keys[keys.length - 1].frame) {
  51882. to++;
  51883. }
  51884. }
  51885. // Compute ratio
  51886. var range = to - from;
  51887. var offsetValue;
  51888. // ratio represents the frame delta between from and to
  51889. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51890. var highLimitValue = 0;
  51891. this._previousDelay = delay;
  51892. this._previousRatio = ratio;
  51893. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51894. returnValue = false;
  51895. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51896. }
  51897. else {
  51898. // Get max value if required
  51899. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51900. var keyOffset = to.toString() + from.toString();
  51901. if (!this._offsetsCache[keyOffset]) {
  51902. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51903. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51904. switch (this._animation.dataType) {
  51905. // Float
  51906. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51907. this._offsetsCache[keyOffset] = toValue - fromValue;
  51908. break;
  51909. // Quaternion
  51910. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51911. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51912. break;
  51913. // Vector3
  51914. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51915. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51916. // Vector2
  51917. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51918. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51919. // Size
  51920. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51921. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51922. // Color3
  51923. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51924. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51925. default:
  51926. break;
  51927. }
  51928. this._highLimitsCache[keyOffset] = toValue;
  51929. }
  51930. highLimitValue = this._highLimitsCache[keyOffset];
  51931. offsetValue = this._offsetsCache[keyOffset];
  51932. }
  51933. }
  51934. if (offsetValue === undefined) {
  51935. switch (this._animation.dataType) {
  51936. // Float
  51937. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51938. offsetValue = 0;
  51939. break;
  51940. // Quaternion
  51941. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51942. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51943. break;
  51944. // Vector3
  51945. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51946. offsetValue = BABYLON.Vector3.Zero();
  51947. break;
  51948. // Vector2
  51949. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51950. offsetValue = BABYLON.Vector2.Zero();
  51951. break;
  51952. // Size
  51953. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51954. offsetValue = BABYLON.Size.Zero();
  51955. break;
  51956. // Color3
  51957. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51958. offsetValue = BABYLON.Color3.Black();
  51959. }
  51960. }
  51961. // Compute value
  51962. var repeatCount = (ratio / range) >> 0;
  51963. var currentFrame = returnValue ? from + ratio % range : to;
  51964. // Need to normalize?
  51965. if (this._host && this._host.syncRoot) {
  51966. var syncRoot = this._host.syncRoot;
  51967. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51968. currentFrame = from + (to - from) * hostNormalizedFrame;
  51969. }
  51970. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51971. // Set value
  51972. this.setValue(currentValue, weight);
  51973. // Check events
  51974. var events = this._animation.getEvents();
  51975. for (var index = 0; index < events.length; index++) {
  51976. // Make sure current frame has passed event frame and that event frame is within the current range
  51977. // Also, handle both forward and reverse animations
  51978. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51979. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51980. var event = events[index];
  51981. if (!event.isDone) {
  51982. // If event should be done only once, remove it.
  51983. if (event.onlyOnce) {
  51984. events.splice(index, 1);
  51985. index--;
  51986. }
  51987. event.isDone = true;
  51988. event.action();
  51989. } // Don't do anything if the event has already be done.
  51990. }
  51991. else if (events[index].isDone && !events[index].onlyOnce) {
  51992. // reset event, the animation is looping
  51993. events[index].isDone = false;
  51994. }
  51995. }
  51996. if (!returnValue) {
  51997. this._stopped = true;
  51998. }
  51999. return returnValue;
  52000. };
  52001. return RuntimeAnimation;
  52002. }());
  52003. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52004. })(BABYLON || (BABYLON = {}));
  52005. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52006. var BABYLON;
  52007. (function (BABYLON) {
  52008. var Animatable = /** @class */ (function () {
  52009. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52010. if (fromFrame === void 0) { fromFrame = 0; }
  52011. if (toFrame === void 0) { toFrame = 100; }
  52012. if (loopAnimation === void 0) { loopAnimation = false; }
  52013. if (speedRatio === void 0) { speedRatio = 1.0; }
  52014. this.target = target;
  52015. this.fromFrame = fromFrame;
  52016. this.toFrame = toFrame;
  52017. this.loopAnimation = loopAnimation;
  52018. this.onAnimationEnd = onAnimationEnd;
  52019. this._localDelayOffset = null;
  52020. this._pausedDelay = null;
  52021. this._runtimeAnimations = new Array();
  52022. this._paused = false;
  52023. this._speedRatio = 1;
  52024. this._weight = -1.0;
  52025. this.animationStarted = false;
  52026. this._scene = scene;
  52027. if (animations) {
  52028. this.appendAnimations(target, animations);
  52029. }
  52030. this._speedRatio = speedRatio;
  52031. scene._activeAnimatables.push(this);
  52032. }
  52033. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52034. /**
  52035. * Gets the root Animatable used to synchronize and normalize animations
  52036. */
  52037. get: function () {
  52038. return this._syncRoot;
  52039. },
  52040. enumerable: true,
  52041. configurable: true
  52042. });
  52043. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52044. /**
  52045. * Gets the current frame of the first RuntimeAnimation
  52046. * Used to synchronize Animatables
  52047. */
  52048. get: function () {
  52049. if (this._runtimeAnimations.length === 0) {
  52050. return 0;
  52051. }
  52052. return this._runtimeAnimations[0].currentFrame;
  52053. },
  52054. enumerable: true,
  52055. configurable: true
  52056. });
  52057. Object.defineProperty(Animatable.prototype, "weight", {
  52058. /**
  52059. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52060. */
  52061. get: function () {
  52062. return this._weight;
  52063. },
  52064. set: function (value) {
  52065. if (value === -1) { // -1 is ok and means no weight
  52066. this._weight = -1;
  52067. return;
  52068. }
  52069. // Else weight must be in [0, 1] range
  52070. this._weight = Math.min(Math.max(value, 0), 1.0);
  52071. },
  52072. enumerable: true,
  52073. configurable: true
  52074. });
  52075. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52076. /**
  52077. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52078. */
  52079. get: function () {
  52080. return this._speedRatio;
  52081. },
  52082. set: function (value) {
  52083. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52084. var animation = this._runtimeAnimations[index];
  52085. animation._prepareForSpeedRatioChange(value);
  52086. }
  52087. this._speedRatio = value;
  52088. },
  52089. enumerable: true,
  52090. configurable: true
  52091. });
  52092. // Methods
  52093. /**
  52094. * Synchronize and normalize current Animatable with a source Animatable
  52095. * This is useful when using animation weights and when animations are not of the same length
  52096. * @param root defines the root Animatable to synchronize with
  52097. * @returns the current Animatable
  52098. */
  52099. Animatable.prototype.syncWith = function (root) {
  52100. this._syncRoot = root;
  52101. if (root) {
  52102. // Make sure this animatable will animate after the root
  52103. var index = this._scene._activeAnimatables.indexOf(this);
  52104. if (index > -1) {
  52105. this._scene._activeAnimatables.splice(index, 1);
  52106. this._scene._activeAnimatables.push(this);
  52107. }
  52108. }
  52109. return this;
  52110. };
  52111. Animatable.prototype.getAnimations = function () {
  52112. return this._runtimeAnimations;
  52113. };
  52114. Animatable.prototype.appendAnimations = function (target, animations) {
  52115. for (var index = 0; index < animations.length; index++) {
  52116. var animation = animations[index];
  52117. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52118. }
  52119. };
  52120. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52121. var runtimeAnimations = this._runtimeAnimations;
  52122. for (var index = 0; index < runtimeAnimations.length; index++) {
  52123. if (runtimeAnimations[index].animation.targetProperty === property) {
  52124. return runtimeAnimations[index].animation;
  52125. }
  52126. }
  52127. return null;
  52128. };
  52129. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52130. var runtimeAnimations = this._runtimeAnimations;
  52131. for (var index = 0; index < runtimeAnimations.length; index++) {
  52132. if (runtimeAnimations[index].animation.targetProperty === property) {
  52133. return runtimeAnimations[index];
  52134. }
  52135. }
  52136. return null;
  52137. };
  52138. Animatable.prototype.reset = function () {
  52139. var runtimeAnimations = this._runtimeAnimations;
  52140. for (var index = 0; index < runtimeAnimations.length; index++) {
  52141. runtimeAnimations[index].reset(true);
  52142. }
  52143. this._localDelayOffset = null;
  52144. this._pausedDelay = null;
  52145. };
  52146. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52147. var runtimeAnimations = this._runtimeAnimations;
  52148. for (var index = 0; index < runtimeAnimations.length; index++) {
  52149. runtimeAnimations[index].animation.enableBlending = true;
  52150. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52151. }
  52152. };
  52153. Animatable.prototype.disableBlending = function () {
  52154. var runtimeAnimations = this._runtimeAnimations;
  52155. for (var index = 0; index < runtimeAnimations.length; index++) {
  52156. runtimeAnimations[index].animation.enableBlending = false;
  52157. }
  52158. };
  52159. Animatable.prototype.goToFrame = function (frame) {
  52160. var runtimeAnimations = this._runtimeAnimations;
  52161. if (runtimeAnimations[0]) {
  52162. var fps = runtimeAnimations[0].animation.framePerSecond;
  52163. var currentFrame = runtimeAnimations[0].currentFrame;
  52164. var adjustTime = frame - currentFrame;
  52165. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52166. if (this._localDelayOffset === null) {
  52167. this._localDelayOffset = 0;
  52168. }
  52169. this._localDelayOffset -= delay;
  52170. }
  52171. for (var index = 0; index < runtimeAnimations.length; index++) {
  52172. runtimeAnimations[index].goToFrame(frame);
  52173. }
  52174. };
  52175. Animatable.prototype.pause = function () {
  52176. if (this._paused) {
  52177. return;
  52178. }
  52179. this._paused = true;
  52180. };
  52181. Animatable.prototype.restart = function () {
  52182. this._paused = false;
  52183. };
  52184. Animatable.prototype.stop = function (animationName) {
  52185. if (animationName) {
  52186. var idx = this._scene._activeAnimatables.indexOf(this);
  52187. if (idx > -1) {
  52188. var runtimeAnimations = this._runtimeAnimations;
  52189. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52190. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52191. continue;
  52192. }
  52193. runtimeAnimations[index].dispose();
  52194. runtimeAnimations.splice(index, 1);
  52195. }
  52196. if (runtimeAnimations.length == 0) {
  52197. this._scene._activeAnimatables.splice(idx, 1);
  52198. if (this.onAnimationEnd) {
  52199. this.onAnimationEnd();
  52200. }
  52201. }
  52202. }
  52203. }
  52204. else {
  52205. var index = this._scene._activeAnimatables.indexOf(this);
  52206. if (index > -1) {
  52207. this._scene._activeAnimatables.splice(index, 1);
  52208. var runtimeAnimations = this._runtimeAnimations;
  52209. for (var index = 0; index < runtimeAnimations.length; index++) {
  52210. runtimeAnimations[index].dispose();
  52211. }
  52212. if (this.onAnimationEnd) {
  52213. this.onAnimationEnd();
  52214. }
  52215. }
  52216. }
  52217. };
  52218. Animatable.prototype._animate = function (delay) {
  52219. if (this._paused) {
  52220. this.animationStarted = false;
  52221. if (this._pausedDelay === null) {
  52222. this._pausedDelay = delay;
  52223. }
  52224. return true;
  52225. }
  52226. if (this._localDelayOffset === null) {
  52227. this._localDelayOffset = delay;
  52228. this._pausedDelay = null;
  52229. }
  52230. else if (this._pausedDelay !== null) {
  52231. this._localDelayOffset += delay - this._pausedDelay;
  52232. this._pausedDelay = null;
  52233. }
  52234. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52235. return true;
  52236. }
  52237. // Animating
  52238. var running = false;
  52239. var runtimeAnimations = this._runtimeAnimations;
  52240. var index;
  52241. for (index = 0; index < runtimeAnimations.length; index++) {
  52242. var animation = runtimeAnimations[index];
  52243. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52244. running = running || isRunning;
  52245. }
  52246. this.animationStarted = running;
  52247. if (!running) {
  52248. // Remove from active animatables
  52249. index = this._scene._activeAnimatables.indexOf(this);
  52250. this._scene._activeAnimatables.splice(index, 1);
  52251. // Dispose all runtime animations
  52252. for (index = 0; index < runtimeAnimations.length; index++) {
  52253. runtimeAnimations[index].dispose();
  52254. }
  52255. }
  52256. if (!running && this.onAnimationEnd) {
  52257. this.onAnimationEnd();
  52258. this.onAnimationEnd = null;
  52259. }
  52260. return running;
  52261. };
  52262. return Animatable;
  52263. }());
  52264. BABYLON.Animatable = Animatable;
  52265. })(BABYLON || (BABYLON = {}));
  52266. //# sourceMappingURL=babylon.animatable.js.map
  52267. var BABYLON;
  52268. (function (BABYLON) {
  52269. var EasingFunction = /** @class */ (function () {
  52270. function EasingFunction() {
  52271. // Properties
  52272. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52273. }
  52274. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52275. get: function () {
  52276. return EasingFunction._EASINGMODE_EASEIN;
  52277. },
  52278. enumerable: true,
  52279. configurable: true
  52280. });
  52281. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52282. get: function () {
  52283. return EasingFunction._EASINGMODE_EASEOUT;
  52284. },
  52285. enumerable: true,
  52286. configurable: true
  52287. });
  52288. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52289. get: function () {
  52290. return EasingFunction._EASINGMODE_EASEINOUT;
  52291. },
  52292. enumerable: true,
  52293. configurable: true
  52294. });
  52295. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52296. var n = Math.min(Math.max(easingMode, 0), 2);
  52297. this._easingMode = n;
  52298. };
  52299. EasingFunction.prototype.getEasingMode = function () {
  52300. return this._easingMode;
  52301. };
  52302. EasingFunction.prototype.easeInCore = function (gradient) {
  52303. throw new Error('You must implement this method');
  52304. };
  52305. EasingFunction.prototype.ease = function (gradient) {
  52306. switch (this._easingMode) {
  52307. case EasingFunction.EASINGMODE_EASEIN:
  52308. return this.easeInCore(gradient);
  52309. case EasingFunction.EASINGMODE_EASEOUT:
  52310. return (1 - this.easeInCore(1 - gradient));
  52311. }
  52312. if (gradient >= 0.5) {
  52313. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52314. }
  52315. return (this.easeInCore(gradient * 2) * 0.5);
  52316. };
  52317. //Statics
  52318. EasingFunction._EASINGMODE_EASEIN = 0;
  52319. EasingFunction._EASINGMODE_EASEOUT = 1;
  52320. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52321. return EasingFunction;
  52322. }());
  52323. BABYLON.EasingFunction = EasingFunction;
  52324. var CircleEase = /** @class */ (function (_super) {
  52325. __extends(CircleEase, _super);
  52326. function CircleEase() {
  52327. return _super !== null && _super.apply(this, arguments) || this;
  52328. }
  52329. CircleEase.prototype.easeInCore = function (gradient) {
  52330. gradient = Math.max(0, Math.min(1, gradient));
  52331. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52332. };
  52333. return CircleEase;
  52334. }(EasingFunction));
  52335. BABYLON.CircleEase = CircleEase;
  52336. var BackEase = /** @class */ (function (_super) {
  52337. __extends(BackEase, _super);
  52338. function BackEase(amplitude) {
  52339. if (amplitude === void 0) { amplitude = 1; }
  52340. var _this = _super.call(this) || this;
  52341. _this.amplitude = amplitude;
  52342. return _this;
  52343. }
  52344. BackEase.prototype.easeInCore = function (gradient) {
  52345. var num = Math.max(0, this.amplitude);
  52346. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52347. };
  52348. return BackEase;
  52349. }(EasingFunction));
  52350. BABYLON.BackEase = BackEase;
  52351. var BounceEase = /** @class */ (function (_super) {
  52352. __extends(BounceEase, _super);
  52353. function BounceEase(bounces, bounciness) {
  52354. if (bounces === void 0) { bounces = 3; }
  52355. if (bounciness === void 0) { bounciness = 2; }
  52356. var _this = _super.call(this) || this;
  52357. _this.bounces = bounces;
  52358. _this.bounciness = bounciness;
  52359. return _this;
  52360. }
  52361. BounceEase.prototype.easeInCore = function (gradient) {
  52362. var y = Math.max(0.0, this.bounces);
  52363. var bounciness = this.bounciness;
  52364. if (bounciness <= 1.0) {
  52365. bounciness = 1.001;
  52366. }
  52367. var num9 = Math.pow(bounciness, y);
  52368. var num5 = 1.0 - bounciness;
  52369. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52370. var num15 = gradient * num4;
  52371. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52372. var num3 = Math.floor(num65);
  52373. var num13 = num3 + 1.0;
  52374. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52375. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52376. var num7 = (num8 + num12) * 0.5;
  52377. var num6 = gradient - num7;
  52378. var num2 = num7 - num8;
  52379. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52380. };
  52381. return BounceEase;
  52382. }(EasingFunction));
  52383. BABYLON.BounceEase = BounceEase;
  52384. var CubicEase = /** @class */ (function (_super) {
  52385. __extends(CubicEase, _super);
  52386. function CubicEase() {
  52387. return _super !== null && _super.apply(this, arguments) || this;
  52388. }
  52389. CubicEase.prototype.easeInCore = function (gradient) {
  52390. return (gradient * gradient * gradient);
  52391. };
  52392. return CubicEase;
  52393. }(EasingFunction));
  52394. BABYLON.CubicEase = CubicEase;
  52395. var ElasticEase = /** @class */ (function (_super) {
  52396. __extends(ElasticEase, _super);
  52397. function ElasticEase(oscillations, springiness) {
  52398. if (oscillations === void 0) { oscillations = 3; }
  52399. if (springiness === void 0) { springiness = 3; }
  52400. var _this = _super.call(this) || this;
  52401. _this.oscillations = oscillations;
  52402. _this.springiness = springiness;
  52403. return _this;
  52404. }
  52405. ElasticEase.prototype.easeInCore = function (gradient) {
  52406. var num2;
  52407. var num3 = Math.max(0.0, this.oscillations);
  52408. var num = Math.max(0.0, this.springiness);
  52409. if (num == 0) {
  52410. num2 = gradient;
  52411. }
  52412. else {
  52413. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52414. }
  52415. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52416. };
  52417. return ElasticEase;
  52418. }(EasingFunction));
  52419. BABYLON.ElasticEase = ElasticEase;
  52420. var ExponentialEase = /** @class */ (function (_super) {
  52421. __extends(ExponentialEase, _super);
  52422. function ExponentialEase(exponent) {
  52423. if (exponent === void 0) { exponent = 2; }
  52424. var _this = _super.call(this) || this;
  52425. _this.exponent = exponent;
  52426. return _this;
  52427. }
  52428. ExponentialEase.prototype.easeInCore = function (gradient) {
  52429. if (this.exponent <= 0) {
  52430. return gradient;
  52431. }
  52432. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52433. };
  52434. return ExponentialEase;
  52435. }(EasingFunction));
  52436. BABYLON.ExponentialEase = ExponentialEase;
  52437. var PowerEase = /** @class */ (function (_super) {
  52438. __extends(PowerEase, _super);
  52439. function PowerEase(power) {
  52440. if (power === void 0) { power = 2; }
  52441. var _this = _super.call(this) || this;
  52442. _this.power = power;
  52443. return _this;
  52444. }
  52445. PowerEase.prototype.easeInCore = function (gradient) {
  52446. var y = Math.max(0.0, this.power);
  52447. return Math.pow(gradient, y);
  52448. };
  52449. return PowerEase;
  52450. }(EasingFunction));
  52451. BABYLON.PowerEase = PowerEase;
  52452. var QuadraticEase = /** @class */ (function (_super) {
  52453. __extends(QuadraticEase, _super);
  52454. function QuadraticEase() {
  52455. return _super !== null && _super.apply(this, arguments) || this;
  52456. }
  52457. QuadraticEase.prototype.easeInCore = function (gradient) {
  52458. return (gradient * gradient);
  52459. };
  52460. return QuadraticEase;
  52461. }(EasingFunction));
  52462. BABYLON.QuadraticEase = QuadraticEase;
  52463. var QuarticEase = /** @class */ (function (_super) {
  52464. __extends(QuarticEase, _super);
  52465. function QuarticEase() {
  52466. return _super !== null && _super.apply(this, arguments) || this;
  52467. }
  52468. QuarticEase.prototype.easeInCore = function (gradient) {
  52469. return (gradient * gradient * gradient * gradient);
  52470. };
  52471. return QuarticEase;
  52472. }(EasingFunction));
  52473. BABYLON.QuarticEase = QuarticEase;
  52474. var QuinticEase = /** @class */ (function (_super) {
  52475. __extends(QuinticEase, _super);
  52476. function QuinticEase() {
  52477. return _super !== null && _super.apply(this, arguments) || this;
  52478. }
  52479. QuinticEase.prototype.easeInCore = function (gradient) {
  52480. return (gradient * gradient * gradient * gradient * gradient);
  52481. };
  52482. return QuinticEase;
  52483. }(EasingFunction));
  52484. BABYLON.QuinticEase = QuinticEase;
  52485. var SineEase = /** @class */ (function (_super) {
  52486. __extends(SineEase, _super);
  52487. function SineEase() {
  52488. return _super !== null && _super.apply(this, arguments) || this;
  52489. }
  52490. SineEase.prototype.easeInCore = function (gradient) {
  52491. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52492. };
  52493. return SineEase;
  52494. }(EasingFunction));
  52495. BABYLON.SineEase = SineEase;
  52496. var BezierCurveEase = /** @class */ (function (_super) {
  52497. __extends(BezierCurveEase, _super);
  52498. function BezierCurveEase(x1, y1, x2, y2) {
  52499. if (x1 === void 0) { x1 = 0; }
  52500. if (y1 === void 0) { y1 = 0; }
  52501. if (x2 === void 0) { x2 = 1; }
  52502. if (y2 === void 0) { y2 = 1; }
  52503. var _this = _super.call(this) || this;
  52504. _this.x1 = x1;
  52505. _this.y1 = y1;
  52506. _this.x2 = x2;
  52507. _this.y2 = y2;
  52508. return _this;
  52509. }
  52510. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52511. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52512. };
  52513. return BezierCurveEase;
  52514. }(EasingFunction));
  52515. BABYLON.BezierCurveEase = BezierCurveEase;
  52516. })(BABYLON || (BABYLON = {}));
  52517. //# sourceMappingURL=babylon.easing.js.map
  52518. var BABYLON;
  52519. (function (BABYLON) {
  52520. /**
  52521. * A Condition applied to an Action
  52522. */
  52523. var Condition = /** @class */ (function () {
  52524. /**
  52525. * Creates a new Condition
  52526. * @param actionManager the manager of the action the condition is applied to
  52527. */
  52528. function Condition(actionManager) {
  52529. this._actionManager = actionManager;
  52530. }
  52531. /**
  52532. * Check if the current condition is valid
  52533. * @returns a boolean
  52534. */
  52535. Condition.prototype.isValid = function () {
  52536. return true;
  52537. };
  52538. /**
  52539. * Internal only
  52540. * @hidden
  52541. */
  52542. Condition.prototype._getProperty = function (propertyPath) {
  52543. return this._actionManager._getProperty(propertyPath);
  52544. };
  52545. /**
  52546. * Internal only
  52547. * @hidden
  52548. */
  52549. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52550. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52551. };
  52552. /**
  52553. * Serialize placeholder for child classes
  52554. * @returns the serialized object
  52555. */
  52556. Condition.prototype.serialize = function () {
  52557. };
  52558. /**
  52559. * Internal only
  52560. * @hidden
  52561. */
  52562. Condition.prototype._serialize = function (serializedCondition) {
  52563. return {
  52564. type: 2,
  52565. children: [],
  52566. name: serializedCondition.name,
  52567. properties: serializedCondition.properties
  52568. };
  52569. };
  52570. return Condition;
  52571. }());
  52572. BABYLON.Condition = Condition;
  52573. /**
  52574. * Defines specific conditional operators as extensions of Condition
  52575. */
  52576. var ValueCondition = /** @class */ (function (_super) {
  52577. __extends(ValueCondition, _super);
  52578. /**
  52579. * Creates a new ValueCondition
  52580. * @param actionManager manager for the action the condition applies to
  52581. * @param target for the action
  52582. * @param propertyPath path to specify the property of the target the conditional operator uses
  52583. * @param value the value compared by the conditional operator against the current value of the property
  52584. * @param operator the conditional operator, default ValueCondition.IsEqual
  52585. */
  52586. function ValueCondition(actionManager, target,
  52587. /** path to specify the property of the target the conditional operator uses */
  52588. propertyPath,
  52589. /** the value compared by the conditional operator against the current value of the property */
  52590. value,
  52591. /** the conditional operator, default ValueCondition.IsEqual */
  52592. operator) {
  52593. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52594. var _this = _super.call(this, actionManager) || this;
  52595. _this.propertyPath = propertyPath;
  52596. _this.value = value;
  52597. _this.operator = operator;
  52598. _this._target = target;
  52599. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52600. _this._property = _this._getProperty(_this.propertyPath);
  52601. return _this;
  52602. }
  52603. Object.defineProperty(ValueCondition, "IsEqual", {
  52604. /**
  52605. * returns the number for IsEqual
  52606. */
  52607. get: function () {
  52608. return ValueCondition._IsEqual;
  52609. },
  52610. enumerable: true,
  52611. configurable: true
  52612. });
  52613. Object.defineProperty(ValueCondition, "IsDifferent", {
  52614. /**
  52615. * Returns the number for IsDifferent
  52616. */
  52617. get: function () {
  52618. return ValueCondition._IsDifferent;
  52619. },
  52620. enumerable: true,
  52621. configurable: true
  52622. });
  52623. Object.defineProperty(ValueCondition, "IsGreater", {
  52624. /**
  52625. * Returns the number for IsGreater
  52626. */
  52627. get: function () {
  52628. return ValueCondition._IsGreater;
  52629. },
  52630. enumerable: true,
  52631. configurable: true
  52632. });
  52633. Object.defineProperty(ValueCondition, "IsLesser", {
  52634. /**
  52635. * Returns the number for IsLesser
  52636. */
  52637. get: function () {
  52638. return ValueCondition._IsLesser;
  52639. },
  52640. enumerable: true,
  52641. configurable: true
  52642. });
  52643. /**
  52644. * Compares the given value with the property value for the specified conditional operator
  52645. * @returns the result of the comparison
  52646. */
  52647. ValueCondition.prototype.isValid = function () {
  52648. switch (this.operator) {
  52649. case ValueCondition.IsGreater:
  52650. return this._effectiveTarget[this._property] > this.value;
  52651. case ValueCondition.IsLesser:
  52652. return this._effectiveTarget[this._property] < this.value;
  52653. case ValueCondition.IsEqual:
  52654. case ValueCondition.IsDifferent:
  52655. var check;
  52656. if (this.value.equals) {
  52657. check = this.value.equals(this._effectiveTarget[this._property]);
  52658. }
  52659. else {
  52660. check = this.value === this._effectiveTarget[this._property];
  52661. }
  52662. return this.operator === ValueCondition.IsEqual ? check : !check;
  52663. }
  52664. return false;
  52665. };
  52666. /**
  52667. * Serialize the ValueCondition into a JSON compatible object
  52668. * @returns serialization object
  52669. */
  52670. ValueCondition.prototype.serialize = function () {
  52671. return this._serialize({
  52672. name: "ValueCondition",
  52673. properties: [
  52674. BABYLON.Action._GetTargetProperty(this._target),
  52675. { name: "propertyPath", value: this.propertyPath },
  52676. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52677. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52678. ]
  52679. });
  52680. };
  52681. /**
  52682. * Gets the name of the conditional operator for the ValueCondition
  52683. * @param operator the conditional operator
  52684. * @returns the name
  52685. */
  52686. ValueCondition.GetOperatorName = function (operator) {
  52687. switch (operator) {
  52688. case ValueCondition._IsEqual: return "IsEqual";
  52689. case ValueCondition._IsDifferent: return "IsDifferent";
  52690. case ValueCondition._IsGreater: return "IsGreater";
  52691. case ValueCondition._IsLesser: return "IsLesser";
  52692. default: return "";
  52693. }
  52694. };
  52695. /**
  52696. * Internal only
  52697. * @hidden
  52698. */
  52699. ValueCondition._IsEqual = 0;
  52700. /**
  52701. * Internal only
  52702. * @hidden
  52703. */
  52704. ValueCondition._IsDifferent = 1;
  52705. /**
  52706. * Internal only
  52707. * @hidden
  52708. */
  52709. ValueCondition._IsGreater = 2;
  52710. /**
  52711. * Internal only
  52712. * @hidden
  52713. */
  52714. ValueCondition._IsLesser = 3;
  52715. return ValueCondition;
  52716. }(Condition));
  52717. BABYLON.ValueCondition = ValueCondition;
  52718. /**
  52719. * Defines a predicate condition as an extension of Condition
  52720. */
  52721. var PredicateCondition = /** @class */ (function (_super) {
  52722. __extends(PredicateCondition, _super);
  52723. /**
  52724. * Creates a new PredicateCondition
  52725. * @param actionManager manager for the action the condition applies to
  52726. * @param predicate defines the predicate function used to validate the condition
  52727. */
  52728. function PredicateCondition(actionManager,
  52729. /** defines the predicate function used to validate the condition */
  52730. predicate) {
  52731. var _this = _super.call(this, actionManager) || this;
  52732. _this.predicate = predicate;
  52733. return _this;
  52734. }
  52735. /**
  52736. * @returns the validity of the predicate condition
  52737. */
  52738. PredicateCondition.prototype.isValid = function () {
  52739. return this.predicate();
  52740. };
  52741. return PredicateCondition;
  52742. }(Condition));
  52743. BABYLON.PredicateCondition = PredicateCondition;
  52744. /**
  52745. * Defines a state condition as an extension of Condition
  52746. */
  52747. var StateCondition = /** @class */ (function (_super) {
  52748. __extends(StateCondition, _super);
  52749. /**
  52750. * Creates a new StateCondition
  52751. * @param actionManager manager for the action the condition applies to
  52752. * @param target of the condition
  52753. * @param value to compare with target state
  52754. */
  52755. function StateCondition(actionManager, target, value) {
  52756. var _this = _super.call(this, actionManager) || this;
  52757. _this.value = value;
  52758. _this._target = target;
  52759. return _this;
  52760. }
  52761. /**
  52762. * @returns the validity of the state
  52763. */
  52764. StateCondition.prototype.isValid = function () {
  52765. return this._target.state === this.value;
  52766. };
  52767. /**
  52768. * Serialize the StateCondition into a JSON compatible object
  52769. * @returns serialization object
  52770. */
  52771. StateCondition.prototype.serialize = function () {
  52772. return this._serialize({
  52773. name: "StateCondition",
  52774. properties: [
  52775. BABYLON.Action._GetTargetProperty(this._target),
  52776. { name: "value", value: this.value }
  52777. ]
  52778. });
  52779. };
  52780. return StateCondition;
  52781. }(Condition));
  52782. BABYLON.StateCondition = StateCondition;
  52783. })(BABYLON || (BABYLON = {}));
  52784. //# sourceMappingURL=babylon.condition.js.map
  52785. var BABYLON;
  52786. (function (BABYLON) {
  52787. /**
  52788. * The action to be carried out following a trigger
  52789. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52790. */
  52791. var Action = /** @class */ (function () {
  52792. /**
  52793. * Creates a new Action
  52794. * @param triggerOptions the trigger, with or without parameters, for the action
  52795. * @param condition an optional determinant of action
  52796. */
  52797. function Action(
  52798. /** the trigger, with or without parameters, for the action */
  52799. triggerOptions, condition) {
  52800. this.triggerOptions = triggerOptions;
  52801. /**
  52802. * An event triggered prior to action being executed.
  52803. */
  52804. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52805. if (triggerOptions.parameter) {
  52806. this.trigger = triggerOptions.trigger;
  52807. this._triggerParameter = triggerOptions.parameter;
  52808. }
  52809. else {
  52810. this.trigger = triggerOptions;
  52811. }
  52812. this._nextActiveAction = this;
  52813. this._condition = condition;
  52814. }
  52815. /**
  52816. * Internal only
  52817. * @hidden
  52818. */
  52819. Action.prototype._prepare = function () {
  52820. };
  52821. /**
  52822. * Gets the trigger parameters
  52823. * @returns the trigger parameters
  52824. */
  52825. Action.prototype.getTriggerParameter = function () {
  52826. return this._triggerParameter;
  52827. };
  52828. /**
  52829. * Internal only - executes current action event
  52830. * @hidden
  52831. */
  52832. Action.prototype._executeCurrent = function (evt) {
  52833. if (this._nextActiveAction._condition) {
  52834. var condition = this._nextActiveAction._condition;
  52835. var currentRenderId = this._actionManager.getScene().getRenderId();
  52836. // We cache the current evaluation for the current frame
  52837. if (condition._evaluationId === currentRenderId) {
  52838. if (!condition._currentResult) {
  52839. return;
  52840. }
  52841. }
  52842. else {
  52843. condition._evaluationId = currentRenderId;
  52844. if (!condition.isValid()) {
  52845. condition._currentResult = false;
  52846. return;
  52847. }
  52848. condition._currentResult = true;
  52849. }
  52850. }
  52851. this.onBeforeExecuteObservable.notifyObservers(this);
  52852. this._nextActiveAction.execute(evt);
  52853. this.skipToNextActiveAction();
  52854. };
  52855. /**
  52856. * Execute placeholder for child classes
  52857. * @param evt optional action event
  52858. */
  52859. Action.prototype.execute = function (evt) {
  52860. };
  52861. /**
  52862. * Skips to next active action
  52863. */
  52864. Action.prototype.skipToNextActiveAction = function () {
  52865. if (this._nextActiveAction._child) {
  52866. if (!this._nextActiveAction._child._actionManager) {
  52867. this._nextActiveAction._child._actionManager = this._actionManager;
  52868. }
  52869. this._nextActiveAction = this._nextActiveAction._child;
  52870. }
  52871. else {
  52872. this._nextActiveAction = this;
  52873. }
  52874. };
  52875. /**
  52876. * Adds action to chain of actions, may be a DoNothingAction
  52877. * @param action defines the next action to execute
  52878. * @returns The action passed in
  52879. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52880. */
  52881. Action.prototype.then = function (action) {
  52882. this._child = action;
  52883. action._actionManager = this._actionManager;
  52884. action._prepare();
  52885. return action;
  52886. };
  52887. /**
  52888. * Internal only
  52889. * @hidden
  52890. */
  52891. Action.prototype._getProperty = function (propertyPath) {
  52892. return this._actionManager._getProperty(propertyPath);
  52893. };
  52894. /**
  52895. * Internal only
  52896. * @hidden
  52897. */
  52898. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52899. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52900. };
  52901. /**
  52902. * Serialize placeholder for child classes
  52903. * @param parent of child
  52904. * @returns the serialized object
  52905. */
  52906. Action.prototype.serialize = function (parent) {
  52907. };
  52908. /**
  52909. * Internal only called by serialize
  52910. * @hidden
  52911. */
  52912. Action.prototype._serialize = function (serializedAction, parent) {
  52913. var serializationObject = {
  52914. type: 1,
  52915. children: [],
  52916. name: serializedAction.name,
  52917. properties: serializedAction.properties || []
  52918. };
  52919. // Serialize child
  52920. if (this._child) {
  52921. this._child.serialize(serializationObject);
  52922. }
  52923. // Check if "this" has a condition
  52924. if (this._condition) {
  52925. var serializedCondition = this._condition.serialize();
  52926. serializedCondition.children.push(serializationObject);
  52927. if (parent) {
  52928. parent.children.push(serializedCondition);
  52929. }
  52930. return serializedCondition;
  52931. }
  52932. if (parent) {
  52933. parent.children.push(serializationObject);
  52934. }
  52935. return serializationObject;
  52936. };
  52937. /**
  52938. * Internal only
  52939. * @hidden
  52940. */
  52941. Action._SerializeValueAsString = function (value) {
  52942. if (typeof value === "number") {
  52943. return value.toString();
  52944. }
  52945. if (typeof value === "boolean") {
  52946. return value ? "true" : "false";
  52947. }
  52948. if (value instanceof BABYLON.Vector2) {
  52949. return value.x + ", " + value.y;
  52950. }
  52951. if (value instanceof BABYLON.Vector3) {
  52952. return value.x + ", " + value.y + ", " + value.z;
  52953. }
  52954. if (value instanceof BABYLON.Color3) {
  52955. return value.r + ", " + value.g + ", " + value.b;
  52956. }
  52957. if (value instanceof BABYLON.Color4) {
  52958. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52959. }
  52960. return value; // string
  52961. };
  52962. /**
  52963. * Internal only
  52964. * @hidden
  52965. */
  52966. Action._GetTargetProperty = function (target) {
  52967. return {
  52968. name: "target",
  52969. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52970. : target instanceof BABYLON.Light ? "LightProperties"
  52971. : target instanceof BABYLON.Camera ? "CameraProperties"
  52972. : "SceneProperties",
  52973. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52974. };
  52975. };
  52976. return Action;
  52977. }());
  52978. BABYLON.Action = Action;
  52979. })(BABYLON || (BABYLON = {}));
  52980. //# sourceMappingURL=babylon.action.js.map
  52981. var BABYLON;
  52982. (function (BABYLON) {
  52983. /**
  52984. * ActionEvent is the event being sent when an action is triggered.
  52985. */
  52986. var ActionEvent = /** @class */ (function () {
  52987. /**
  52988. * Creates a new ActionEvent
  52989. * @param source The mesh or sprite that triggered the action
  52990. * @param pointerX The X mouse cursor position at the time of the event
  52991. * @param pointerY The Y mouse cursor position at the time of the event
  52992. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52993. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52994. * @param additionalData additional data for the event
  52995. */
  52996. function ActionEvent(
  52997. /** The mesh or sprite that triggered the action */
  52998. source,
  52999. /** The X mouse cursor position at the time of the event */
  53000. pointerX,
  53001. /** The Y mouse cursor position at the time of the event */
  53002. pointerY,
  53003. /** The mesh that is currently pointed at (can be null) */
  53004. meshUnderPointer,
  53005. /** the original (browser) event that triggered the ActionEvent */
  53006. sourceEvent,
  53007. /** additional data for the event */
  53008. additionalData) {
  53009. this.source = source;
  53010. this.pointerX = pointerX;
  53011. this.pointerY = pointerY;
  53012. this.meshUnderPointer = meshUnderPointer;
  53013. this.sourceEvent = sourceEvent;
  53014. this.additionalData = additionalData;
  53015. }
  53016. /**
  53017. * Helper function to auto-create an ActionEvent from a source mesh.
  53018. * @param source The source mesh that triggered the event
  53019. * @param evt The original (browser) event
  53020. * @param additionalData additional data for the event
  53021. * @returns the new ActionEvent
  53022. */
  53023. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53024. var scene = source.getScene();
  53025. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53026. };
  53027. /**
  53028. * Helper function to auto-create an ActionEvent from a source sprite
  53029. * @param source The source sprite that triggered the event
  53030. * @param scene Scene associated with the sprite
  53031. * @param evt The original (browser) event
  53032. * @param additionalData additional data for the event
  53033. * @returns the new ActionEvent
  53034. */
  53035. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53036. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53037. };
  53038. /**
  53039. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53040. * @param scene the scene where the event occurred
  53041. * @param evt The original (browser) event
  53042. * @returns the new ActionEvent
  53043. */
  53044. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53045. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53046. };
  53047. /**
  53048. * Helper function to auto-create an ActionEvent from a primitive
  53049. * @param prim defines the target primitive
  53050. * @param pointerPos defines the pointer position
  53051. * @param evt The original (browser) event
  53052. * @param additionalData additional data for the event
  53053. * @returns the new ActionEvent
  53054. */
  53055. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53056. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53057. };
  53058. return ActionEvent;
  53059. }());
  53060. BABYLON.ActionEvent = ActionEvent;
  53061. /**
  53062. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53063. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53064. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53065. */
  53066. var ActionManager = /** @class */ (function () {
  53067. /**
  53068. * Creates a new action manager
  53069. * @param scene defines the hosting scene
  53070. */
  53071. function ActionManager(scene) {
  53072. // Members
  53073. /** Gets the list of actions */
  53074. this.actions = new Array();
  53075. /** Gets the cursor to use when hovering items */
  53076. this.hoverCursor = '';
  53077. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53078. scene._actionManagers.push(this);
  53079. }
  53080. Object.defineProperty(ActionManager, "NothingTrigger", {
  53081. /**
  53082. * Nothing
  53083. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53084. */
  53085. get: function () {
  53086. return ActionManager._NothingTrigger;
  53087. },
  53088. enumerable: true,
  53089. configurable: true
  53090. });
  53091. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53092. /**
  53093. * On pick
  53094. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53095. */
  53096. get: function () {
  53097. return ActionManager._OnPickTrigger;
  53098. },
  53099. enumerable: true,
  53100. configurable: true
  53101. });
  53102. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53103. /**
  53104. * On left pick
  53105. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53106. */
  53107. get: function () {
  53108. return ActionManager._OnLeftPickTrigger;
  53109. },
  53110. enumerable: true,
  53111. configurable: true
  53112. });
  53113. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53114. /**
  53115. * On right pick
  53116. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53117. */
  53118. get: function () {
  53119. return ActionManager._OnRightPickTrigger;
  53120. },
  53121. enumerable: true,
  53122. configurable: true
  53123. });
  53124. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53125. /**
  53126. * On center pick
  53127. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53128. */
  53129. get: function () {
  53130. return ActionManager._OnCenterPickTrigger;
  53131. },
  53132. enumerable: true,
  53133. configurable: true
  53134. });
  53135. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53136. /**
  53137. * On pick down
  53138. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53139. */
  53140. get: function () {
  53141. return ActionManager._OnPickDownTrigger;
  53142. },
  53143. enumerable: true,
  53144. configurable: true
  53145. });
  53146. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53147. /**
  53148. * On double pick
  53149. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53150. */
  53151. get: function () {
  53152. return ActionManager._OnDoublePickTrigger;
  53153. },
  53154. enumerable: true,
  53155. configurable: true
  53156. });
  53157. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53158. /**
  53159. * On pick up
  53160. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53161. */
  53162. get: function () {
  53163. return ActionManager._OnPickUpTrigger;
  53164. },
  53165. enumerable: true,
  53166. configurable: true
  53167. });
  53168. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53169. /**
  53170. * On pick out.
  53171. * This trigger will only be raised if you also declared a OnPickDown
  53172. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53173. */
  53174. get: function () {
  53175. return ActionManager._OnPickOutTrigger;
  53176. },
  53177. enumerable: true,
  53178. configurable: true
  53179. });
  53180. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53181. /**
  53182. * On long press
  53183. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53184. */
  53185. get: function () {
  53186. return ActionManager._OnLongPressTrigger;
  53187. },
  53188. enumerable: true,
  53189. configurable: true
  53190. });
  53191. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53192. /**
  53193. * On pointer over
  53194. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53195. */
  53196. get: function () {
  53197. return ActionManager._OnPointerOverTrigger;
  53198. },
  53199. enumerable: true,
  53200. configurable: true
  53201. });
  53202. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53203. /**
  53204. * On pointer out
  53205. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53206. */
  53207. get: function () {
  53208. return ActionManager._OnPointerOutTrigger;
  53209. },
  53210. enumerable: true,
  53211. configurable: true
  53212. });
  53213. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53214. /**
  53215. * On every frame
  53216. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53217. */
  53218. get: function () {
  53219. return ActionManager._OnEveryFrameTrigger;
  53220. },
  53221. enumerable: true,
  53222. configurable: true
  53223. });
  53224. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53225. /**
  53226. * On intersection enter
  53227. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53228. */
  53229. get: function () {
  53230. return ActionManager._OnIntersectionEnterTrigger;
  53231. },
  53232. enumerable: true,
  53233. configurable: true
  53234. });
  53235. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53236. /**
  53237. * On intersection exit
  53238. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53239. */
  53240. get: function () {
  53241. return ActionManager._OnIntersectionExitTrigger;
  53242. },
  53243. enumerable: true,
  53244. configurable: true
  53245. });
  53246. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53247. /**
  53248. * On key down
  53249. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53250. */
  53251. get: function () {
  53252. return ActionManager._OnKeyDownTrigger;
  53253. },
  53254. enumerable: true,
  53255. configurable: true
  53256. });
  53257. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53258. /**
  53259. * On key up
  53260. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53261. */
  53262. get: function () {
  53263. return ActionManager._OnKeyUpTrigger;
  53264. },
  53265. enumerable: true,
  53266. configurable: true
  53267. });
  53268. // Methods
  53269. /**
  53270. * Releases all associated resources
  53271. */
  53272. ActionManager.prototype.dispose = function () {
  53273. var index = this._scene._actionManagers.indexOf(this);
  53274. for (var i = 0; i < this.actions.length; i++) {
  53275. var action = this.actions[i];
  53276. ActionManager.Triggers[action.trigger]--;
  53277. if (ActionManager.Triggers[action.trigger] === 0) {
  53278. delete ActionManager.Triggers[action.trigger];
  53279. }
  53280. }
  53281. if (index > -1) {
  53282. this._scene._actionManagers.splice(index, 1);
  53283. }
  53284. };
  53285. /**
  53286. * Gets hosting scene
  53287. * @returns the hosting scene
  53288. */
  53289. ActionManager.prototype.getScene = function () {
  53290. return this._scene;
  53291. };
  53292. /**
  53293. * Does this action manager handles actions of any of the given triggers
  53294. * @param triggers defines the triggers to be tested
  53295. * @return a boolean indicating whether one (or more) of the triggers is handled
  53296. */
  53297. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53298. for (var index = 0; index < this.actions.length; index++) {
  53299. var action = this.actions[index];
  53300. if (triggers.indexOf(action.trigger) > -1) {
  53301. return true;
  53302. }
  53303. }
  53304. return false;
  53305. };
  53306. /**
  53307. * Does this action manager handles actions of a given trigger
  53308. * @param trigger defines the trigger to be tested
  53309. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53310. * @return whether the trigger is handled
  53311. */
  53312. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53313. for (var index = 0; index < this.actions.length; index++) {
  53314. var action = this.actions[index];
  53315. if (action.trigger === trigger) {
  53316. if (parameterPredicate) {
  53317. if (parameterPredicate(action.getTriggerParameter())) {
  53318. return true;
  53319. }
  53320. }
  53321. else {
  53322. return true;
  53323. }
  53324. }
  53325. }
  53326. return false;
  53327. };
  53328. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53329. /**
  53330. * Does this action manager has pointer triggers
  53331. */
  53332. get: function () {
  53333. for (var index = 0; index < this.actions.length; index++) {
  53334. var action = this.actions[index];
  53335. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53336. return true;
  53337. }
  53338. }
  53339. return false;
  53340. },
  53341. enumerable: true,
  53342. configurable: true
  53343. });
  53344. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53345. /**
  53346. * Does this action manager has pick triggers
  53347. */
  53348. get: function () {
  53349. for (var index = 0; index < this.actions.length; index++) {
  53350. var action = this.actions[index];
  53351. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53352. return true;
  53353. }
  53354. }
  53355. return false;
  53356. },
  53357. enumerable: true,
  53358. configurable: true
  53359. });
  53360. Object.defineProperty(ActionManager, "HasTriggers", {
  53361. /**
  53362. * Does exist one action manager with at least one trigger
  53363. **/
  53364. get: function () {
  53365. for (var t in ActionManager.Triggers) {
  53366. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53367. return true;
  53368. }
  53369. }
  53370. return false;
  53371. },
  53372. enumerable: true,
  53373. configurable: true
  53374. });
  53375. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53376. /**
  53377. * Does exist one action manager with at least one pick trigger
  53378. **/
  53379. get: function () {
  53380. for (var t in ActionManager.Triggers) {
  53381. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53382. var t_int = parseInt(t);
  53383. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53384. return true;
  53385. }
  53386. }
  53387. }
  53388. return false;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. /**
  53394. * Does exist one action manager that handles actions of a given trigger
  53395. * @param trigger defines the trigger to be tested
  53396. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53397. **/
  53398. ActionManager.HasSpecificTrigger = function (trigger) {
  53399. for (var t in ActionManager.Triggers) {
  53400. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53401. var t_int = parseInt(t);
  53402. if (t_int === trigger) {
  53403. return true;
  53404. }
  53405. }
  53406. }
  53407. return false;
  53408. };
  53409. /**
  53410. * Registers an action to this action manager
  53411. * @param action defines the action to be registered
  53412. * @return the action amended (prepared) after registration
  53413. */
  53414. ActionManager.prototype.registerAction = function (action) {
  53415. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53416. if (this.getScene().actionManager !== this) {
  53417. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53418. return null;
  53419. }
  53420. }
  53421. this.actions.push(action);
  53422. if (ActionManager.Triggers[action.trigger]) {
  53423. ActionManager.Triggers[action.trigger]++;
  53424. }
  53425. else {
  53426. ActionManager.Triggers[action.trigger] = 1;
  53427. }
  53428. action._actionManager = this;
  53429. action._prepare();
  53430. return action;
  53431. };
  53432. /**
  53433. * Unregisters an action to this action manager
  53434. * @param action defines the action to be unregistered
  53435. * @return a boolean indicating whether the action has been unregistered
  53436. */
  53437. ActionManager.prototype.unregisterAction = function (action) {
  53438. var index = this.actions.indexOf(action);
  53439. if (index !== -1) {
  53440. this.actions.splice(index, 1);
  53441. ActionManager.Triggers[action.trigger] -= 1;
  53442. if (ActionManager.Triggers[action.trigger] === 0) {
  53443. delete ActionManager.Triggers[action.trigger];
  53444. }
  53445. delete action._actionManager;
  53446. return true;
  53447. }
  53448. return false;
  53449. };
  53450. /**
  53451. * Process a specific trigger
  53452. * @param trigger defines the trigger to process
  53453. * @param evt defines the event details to be processed
  53454. */
  53455. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53456. for (var index = 0; index < this.actions.length; index++) {
  53457. var action = this.actions[index];
  53458. if (action.trigger === trigger) {
  53459. if (evt) {
  53460. if (trigger === ActionManager.OnKeyUpTrigger
  53461. || trigger === ActionManager.OnKeyDownTrigger) {
  53462. var parameter = action.getTriggerParameter();
  53463. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53464. if (!parameter.toLowerCase) {
  53465. continue;
  53466. }
  53467. var lowerCase = parameter.toLowerCase();
  53468. if (lowerCase !== evt.sourceEvent.key) {
  53469. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53470. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53471. if (actualkey !== lowerCase) {
  53472. continue;
  53473. }
  53474. }
  53475. }
  53476. }
  53477. }
  53478. action._executeCurrent(evt);
  53479. }
  53480. }
  53481. };
  53482. /** @hidden */
  53483. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53484. var properties = propertyPath.split(".");
  53485. for (var index = 0; index < properties.length - 1; index++) {
  53486. target = target[properties[index]];
  53487. }
  53488. return target;
  53489. };
  53490. /** @hidden */
  53491. ActionManager.prototype._getProperty = function (propertyPath) {
  53492. var properties = propertyPath.split(".");
  53493. return properties[properties.length - 1];
  53494. };
  53495. /**
  53496. * Serialize this manager to a JSON object
  53497. * @param name defines the property name to store this manager
  53498. * @returns a JSON representation of this manager
  53499. */
  53500. ActionManager.prototype.serialize = function (name) {
  53501. var root = {
  53502. children: new Array(),
  53503. name: name,
  53504. type: 3,
  53505. properties: new Array() // Empty for root but required
  53506. };
  53507. for (var i = 0; i < this.actions.length; i++) {
  53508. var triggerObject = {
  53509. type: 0,
  53510. children: new Array(),
  53511. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53512. properties: new Array()
  53513. };
  53514. var triggerOptions = this.actions[i].triggerOptions;
  53515. if (triggerOptions && typeof triggerOptions !== "number") {
  53516. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53517. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53518. }
  53519. else {
  53520. var parameter = {};
  53521. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53522. if (triggerOptions.parameter.mesh) {
  53523. parameter._meshId = triggerOptions.parameter.mesh.id;
  53524. }
  53525. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53526. }
  53527. }
  53528. // Serialize child action, recursively
  53529. this.actions[i].serialize(triggerObject);
  53530. // Add serialized trigger
  53531. root.children.push(triggerObject);
  53532. }
  53533. return root;
  53534. };
  53535. /**
  53536. * Creates a new ActionManager from a JSON data
  53537. * @param parsedActions defines the JSON data to read from
  53538. * @param object defines the hosting mesh
  53539. * @param scene defines the hosting scene
  53540. */
  53541. ActionManager.Parse = function (parsedActions, object, scene) {
  53542. var actionManager = new ActionManager(scene);
  53543. if (object === null)
  53544. scene.actionManager = actionManager;
  53545. else
  53546. object.actionManager = actionManager;
  53547. // instanciate a new object
  53548. var instanciate = function (name, params) {
  53549. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53550. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53551. newInstance.constructor.apply(newInstance, params);
  53552. return newInstance;
  53553. };
  53554. var parseParameter = function (name, value, target, propertyPath) {
  53555. if (propertyPath === null) {
  53556. // String, boolean or float
  53557. var floatValue = parseFloat(value);
  53558. if (value === "true" || value === "false")
  53559. return value === "true";
  53560. else
  53561. return isNaN(floatValue) ? value : floatValue;
  53562. }
  53563. var effectiveTarget = propertyPath.split(".");
  53564. var values = value.split(",");
  53565. // Get effective Target
  53566. for (var i = 0; i < effectiveTarget.length; i++) {
  53567. target = target[effectiveTarget[i]];
  53568. }
  53569. // Return appropriate value with its type
  53570. if (typeof (target) === "boolean")
  53571. return values[0] === "true";
  53572. if (typeof (target) === "string")
  53573. return values[0];
  53574. // Parameters with multiple values such as Vector3 etc.
  53575. var split = new Array();
  53576. for (var i = 0; i < values.length; i++)
  53577. split.push(parseFloat(values[i]));
  53578. if (target instanceof BABYLON.Vector3)
  53579. return BABYLON.Vector3.FromArray(split);
  53580. if (target instanceof BABYLON.Vector4)
  53581. return BABYLON.Vector4.FromArray(split);
  53582. if (target instanceof BABYLON.Color3)
  53583. return BABYLON.Color3.FromArray(split);
  53584. if (target instanceof BABYLON.Color4)
  53585. return BABYLON.Color4.FromArray(split);
  53586. return parseFloat(values[0]);
  53587. };
  53588. // traverse graph per trigger
  53589. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53590. if (combineArray === void 0) { combineArray = null; }
  53591. if (parsedAction.detached)
  53592. return;
  53593. var parameters = new Array();
  53594. var target = null;
  53595. var propertyPath = null;
  53596. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53597. // Parameters
  53598. if (parsedAction.type === 2)
  53599. parameters.push(actionManager);
  53600. else
  53601. parameters.push(trigger);
  53602. if (combine) {
  53603. var actions = new Array();
  53604. for (var j = 0; j < parsedAction.combine.length; j++) {
  53605. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53606. }
  53607. parameters.push(actions);
  53608. }
  53609. else {
  53610. for (var i = 0; i < parsedAction.properties.length; i++) {
  53611. var value = parsedAction.properties[i].value;
  53612. var name = parsedAction.properties[i].name;
  53613. var targetType = parsedAction.properties[i].targetType;
  53614. if (name === "target")
  53615. if (targetType !== null && targetType === "SceneProperties")
  53616. value = target = scene;
  53617. else
  53618. value = target = scene.getNodeByName(value);
  53619. else if (name === "parent")
  53620. value = scene.getNodeByName(value);
  53621. else if (name === "sound")
  53622. value = scene.getSoundByName(value);
  53623. else if (name !== "propertyPath") {
  53624. if (parsedAction.type === 2 && name === "operator")
  53625. value = BABYLON.ValueCondition[value];
  53626. else
  53627. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53628. }
  53629. else {
  53630. propertyPath = value;
  53631. }
  53632. parameters.push(value);
  53633. }
  53634. }
  53635. if (combineArray === null) {
  53636. parameters.push(condition);
  53637. }
  53638. else {
  53639. parameters.push(null);
  53640. }
  53641. // If interpolate value action
  53642. if (parsedAction.name === "InterpolateValueAction") {
  53643. var param = parameters[parameters.length - 2];
  53644. parameters[parameters.length - 1] = param;
  53645. parameters[parameters.length - 2] = condition;
  53646. }
  53647. // Action or condition(s) and not CombineAction
  53648. var newAction = instanciate(parsedAction.name, parameters);
  53649. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53650. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53651. if (action)
  53652. action.then(nothing);
  53653. else
  53654. actionManager.registerAction(nothing);
  53655. action = nothing;
  53656. }
  53657. if (combineArray === null) {
  53658. if (newAction instanceof BABYLON.Condition) {
  53659. condition = newAction;
  53660. newAction = action;
  53661. }
  53662. else {
  53663. condition = null;
  53664. if (action)
  53665. action.then(newAction);
  53666. else
  53667. actionManager.registerAction(newAction);
  53668. }
  53669. }
  53670. else {
  53671. combineArray.push(newAction);
  53672. }
  53673. for (var i = 0; i < parsedAction.children.length; i++)
  53674. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53675. };
  53676. // triggers
  53677. for (var i = 0; i < parsedActions.children.length; i++) {
  53678. var triggerParams;
  53679. var trigger = parsedActions.children[i];
  53680. if (trigger.properties.length > 0) {
  53681. var param = trigger.properties[0].value;
  53682. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53683. if (value._meshId) {
  53684. value.mesh = scene.getMeshByID(value._meshId);
  53685. }
  53686. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53687. }
  53688. else
  53689. triggerParams = ActionManager[trigger.name];
  53690. for (var j = 0; j < trigger.children.length; j++) {
  53691. if (!trigger.detached)
  53692. traverse(trigger.children[j], triggerParams, null, null);
  53693. }
  53694. }
  53695. };
  53696. /**
  53697. * Get a trigger name by index
  53698. * @param trigger defines the trigger index
  53699. * @returns a trigger name
  53700. */
  53701. ActionManager.GetTriggerName = function (trigger) {
  53702. switch (trigger) {
  53703. case 0: return "NothingTrigger";
  53704. case 1: return "OnPickTrigger";
  53705. case 2: return "OnLeftPickTrigger";
  53706. case 3: return "OnRightPickTrigger";
  53707. case 4: return "OnCenterPickTrigger";
  53708. case 5: return "OnPickDownTrigger";
  53709. case 6: return "OnPickUpTrigger";
  53710. case 7: return "OnLongPressTrigger";
  53711. case 8: return "OnPointerOverTrigger";
  53712. case 9: return "OnPointerOutTrigger";
  53713. case 10: return "OnEveryFrameTrigger";
  53714. case 11: return "OnIntersectionEnterTrigger";
  53715. case 12: return "OnIntersectionExitTrigger";
  53716. case 13: return "OnKeyDownTrigger";
  53717. case 14: return "OnKeyUpTrigger";
  53718. case 15: return "OnPickOutTrigger";
  53719. default: return "";
  53720. }
  53721. };
  53722. // Statics
  53723. ActionManager._NothingTrigger = 0;
  53724. ActionManager._OnPickTrigger = 1;
  53725. ActionManager._OnLeftPickTrigger = 2;
  53726. ActionManager._OnRightPickTrigger = 3;
  53727. ActionManager._OnCenterPickTrigger = 4;
  53728. ActionManager._OnPickDownTrigger = 5;
  53729. ActionManager._OnDoublePickTrigger = 6;
  53730. ActionManager._OnPickUpTrigger = 7;
  53731. ActionManager._OnLongPressTrigger = 8;
  53732. ActionManager._OnPointerOverTrigger = 9;
  53733. ActionManager._OnPointerOutTrigger = 10;
  53734. ActionManager._OnEveryFrameTrigger = 11;
  53735. ActionManager._OnIntersectionEnterTrigger = 12;
  53736. ActionManager._OnIntersectionExitTrigger = 13;
  53737. ActionManager._OnKeyDownTrigger = 14;
  53738. ActionManager._OnKeyUpTrigger = 15;
  53739. ActionManager._OnPickOutTrigger = 16;
  53740. /** Gets the list of active triggers */
  53741. ActionManager.Triggers = {};
  53742. return ActionManager;
  53743. }());
  53744. BABYLON.ActionManager = ActionManager;
  53745. })(BABYLON || (BABYLON = {}));
  53746. //# sourceMappingURL=babylon.actionManager.js.map
  53747. var BABYLON;
  53748. (function (BABYLON) {
  53749. var InterpolateValueAction = /** @class */ (function (_super) {
  53750. __extends(InterpolateValueAction, _super);
  53751. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53752. if (duration === void 0) { duration = 1000; }
  53753. var _this = _super.call(this, triggerOptions, condition) || this;
  53754. _this.propertyPath = propertyPath;
  53755. _this.value = value;
  53756. _this.duration = duration;
  53757. _this.stopOtherAnimations = stopOtherAnimations;
  53758. _this.onInterpolationDone = onInterpolationDone;
  53759. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53760. _this._target = _this._effectiveTarget = target;
  53761. return _this;
  53762. }
  53763. InterpolateValueAction.prototype._prepare = function () {
  53764. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53765. this._property = this._getProperty(this.propertyPath);
  53766. };
  53767. InterpolateValueAction.prototype.execute = function () {
  53768. var _this = this;
  53769. var scene = this._actionManager.getScene();
  53770. var keys = [
  53771. {
  53772. frame: 0,
  53773. value: this._effectiveTarget[this._property]
  53774. }, {
  53775. frame: 100,
  53776. value: this.value
  53777. }
  53778. ];
  53779. var dataType;
  53780. if (typeof this.value === "number") {
  53781. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53782. }
  53783. else if (this.value instanceof BABYLON.Color3) {
  53784. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53785. }
  53786. else if (this.value instanceof BABYLON.Vector3) {
  53787. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53788. }
  53789. else if (this.value instanceof BABYLON.Matrix) {
  53790. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53791. }
  53792. else if (this.value instanceof BABYLON.Quaternion) {
  53793. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53794. }
  53795. else {
  53796. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53797. return;
  53798. }
  53799. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53800. animation.setKeys(keys);
  53801. if (this.stopOtherAnimations) {
  53802. scene.stopAnimation(this._effectiveTarget);
  53803. }
  53804. var wrapper = function () {
  53805. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53806. if (_this.onInterpolationDone) {
  53807. _this.onInterpolationDone();
  53808. }
  53809. };
  53810. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53811. };
  53812. InterpolateValueAction.prototype.serialize = function (parent) {
  53813. return _super.prototype._serialize.call(this, {
  53814. name: "InterpolateValueAction",
  53815. properties: [
  53816. BABYLON.Action._GetTargetProperty(this._target),
  53817. { name: "propertyPath", value: this.propertyPath },
  53818. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53819. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53820. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53821. ]
  53822. }, parent);
  53823. };
  53824. return InterpolateValueAction;
  53825. }(BABYLON.Action));
  53826. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53827. })(BABYLON || (BABYLON = {}));
  53828. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53829. var BABYLON;
  53830. (function (BABYLON) {
  53831. var SwitchBooleanAction = /** @class */ (function (_super) {
  53832. __extends(SwitchBooleanAction, _super);
  53833. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53834. var _this = _super.call(this, triggerOptions, condition) || this;
  53835. _this.propertyPath = propertyPath;
  53836. _this._target = _this._effectiveTarget = target;
  53837. return _this;
  53838. }
  53839. SwitchBooleanAction.prototype._prepare = function () {
  53840. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53841. this._property = this._getProperty(this.propertyPath);
  53842. };
  53843. SwitchBooleanAction.prototype.execute = function () {
  53844. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53845. };
  53846. SwitchBooleanAction.prototype.serialize = function (parent) {
  53847. return _super.prototype._serialize.call(this, {
  53848. name: "SwitchBooleanAction",
  53849. properties: [
  53850. BABYLON.Action._GetTargetProperty(this._target),
  53851. { name: "propertyPath", value: this.propertyPath }
  53852. ]
  53853. }, parent);
  53854. };
  53855. return SwitchBooleanAction;
  53856. }(BABYLON.Action));
  53857. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53858. var SetStateAction = /** @class */ (function (_super) {
  53859. __extends(SetStateAction, _super);
  53860. function SetStateAction(triggerOptions, target, value, condition) {
  53861. var _this = _super.call(this, triggerOptions, condition) || this;
  53862. _this.value = value;
  53863. _this._target = target;
  53864. return _this;
  53865. }
  53866. SetStateAction.prototype.execute = function () {
  53867. this._target.state = this.value;
  53868. };
  53869. SetStateAction.prototype.serialize = function (parent) {
  53870. return _super.prototype._serialize.call(this, {
  53871. name: "SetStateAction",
  53872. properties: [
  53873. BABYLON.Action._GetTargetProperty(this._target),
  53874. { name: "value", value: this.value }
  53875. ]
  53876. }, parent);
  53877. };
  53878. return SetStateAction;
  53879. }(BABYLON.Action));
  53880. BABYLON.SetStateAction = SetStateAction;
  53881. var SetValueAction = /** @class */ (function (_super) {
  53882. __extends(SetValueAction, _super);
  53883. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53884. var _this = _super.call(this, triggerOptions, condition) || this;
  53885. _this.propertyPath = propertyPath;
  53886. _this.value = value;
  53887. _this._target = _this._effectiveTarget = target;
  53888. return _this;
  53889. }
  53890. SetValueAction.prototype._prepare = function () {
  53891. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53892. this._property = this._getProperty(this.propertyPath);
  53893. };
  53894. SetValueAction.prototype.execute = function () {
  53895. this._effectiveTarget[this._property] = this.value;
  53896. if (this._target.markAsDirty) {
  53897. this._target.markAsDirty(this._property);
  53898. }
  53899. };
  53900. SetValueAction.prototype.serialize = function (parent) {
  53901. return _super.prototype._serialize.call(this, {
  53902. name: "SetValueAction",
  53903. properties: [
  53904. BABYLON.Action._GetTargetProperty(this._target),
  53905. { name: "propertyPath", value: this.propertyPath },
  53906. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53907. ]
  53908. }, parent);
  53909. };
  53910. return SetValueAction;
  53911. }(BABYLON.Action));
  53912. BABYLON.SetValueAction = SetValueAction;
  53913. var IncrementValueAction = /** @class */ (function (_super) {
  53914. __extends(IncrementValueAction, _super);
  53915. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53916. var _this = _super.call(this, triggerOptions, condition) || this;
  53917. _this.propertyPath = propertyPath;
  53918. _this.value = value;
  53919. _this._target = _this._effectiveTarget = target;
  53920. return _this;
  53921. }
  53922. IncrementValueAction.prototype._prepare = function () {
  53923. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53924. this._property = this._getProperty(this.propertyPath);
  53925. if (typeof this._effectiveTarget[this._property] !== "number") {
  53926. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53927. }
  53928. };
  53929. IncrementValueAction.prototype.execute = function () {
  53930. this._effectiveTarget[this._property] += this.value;
  53931. if (this._target.markAsDirty) {
  53932. this._target.markAsDirty(this._property);
  53933. }
  53934. };
  53935. IncrementValueAction.prototype.serialize = function (parent) {
  53936. return _super.prototype._serialize.call(this, {
  53937. name: "IncrementValueAction",
  53938. properties: [
  53939. BABYLON.Action._GetTargetProperty(this._target),
  53940. { name: "propertyPath", value: this.propertyPath },
  53941. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53942. ]
  53943. }, parent);
  53944. };
  53945. return IncrementValueAction;
  53946. }(BABYLON.Action));
  53947. BABYLON.IncrementValueAction = IncrementValueAction;
  53948. var PlayAnimationAction = /** @class */ (function (_super) {
  53949. __extends(PlayAnimationAction, _super);
  53950. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53951. var _this = _super.call(this, triggerOptions, condition) || this;
  53952. _this.from = from;
  53953. _this.to = to;
  53954. _this.loop = loop;
  53955. _this._target = target;
  53956. return _this;
  53957. }
  53958. PlayAnimationAction.prototype._prepare = function () {
  53959. };
  53960. PlayAnimationAction.prototype.execute = function () {
  53961. var scene = this._actionManager.getScene();
  53962. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53963. };
  53964. PlayAnimationAction.prototype.serialize = function (parent) {
  53965. return _super.prototype._serialize.call(this, {
  53966. name: "PlayAnimationAction",
  53967. properties: [
  53968. BABYLON.Action._GetTargetProperty(this._target),
  53969. { name: "from", value: String(this.from) },
  53970. { name: "to", value: String(this.to) },
  53971. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53972. ]
  53973. }, parent);
  53974. };
  53975. return PlayAnimationAction;
  53976. }(BABYLON.Action));
  53977. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53978. var StopAnimationAction = /** @class */ (function (_super) {
  53979. __extends(StopAnimationAction, _super);
  53980. function StopAnimationAction(triggerOptions, target, condition) {
  53981. var _this = _super.call(this, triggerOptions, condition) || this;
  53982. _this._target = target;
  53983. return _this;
  53984. }
  53985. StopAnimationAction.prototype._prepare = function () {
  53986. };
  53987. StopAnimationAction.prototype.execute = function () {
  53988. var scene = this._actionManager.getScene();
  53989. scene.stopAnimation(this._target);
  53990. };
  53991. StopAnimationAction.prototype.serialize = function (parent) {
  53992. return _super.prototype._serialize.call(this, {
  53993. name: "StopAnimationAction",
  53994. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53995. }, parent);
  53996. };
  53997. return StopAnimationAction;
  53998. }(BABYLON.Action));
  53999. BABYLON.StopAnimationAction = StopAnimationAction;
  54000. var DoNothingAction = /** @class */ (function (_super) {
  54001. __extends(DoNothingAction, _super);
  54002. function DoNothingAction(triggerOptions, condition) {
  54003. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54004. return _super.call(this, triggerOptions, condition) || this;
  54005. }
  54006. DoNothingAction.prototype.execute = function () {
  54007. };
  54008. DoNothingAction.prototype.serialize = function (parent) {
  54009. return _super.prototype._serialize.call(this, {
  54010. name: "DoNothingAction",
  54011. properties: []
  54012. }, parent);
  54013. };
  54014. return DoNothingAction;
  54015. }(BABYLON.Action));
  54016. BABYLON.DoNothingAction = DoNothingAction;
  54017. var CombineAction = /** @class */ (function (_super) {
  54018. __extends(CombineAction, _super);
  54019. function CombineAction(triggerOptions, children, condition) {
  54020. var _this = _super.call(this, triggerOptions, condition) || this;
  54021. _this.children = children;
  54022. return _this;
  54023. }
  54024. CombineAction.prototype._prepare = function () {
  54025. for (var index = 0; index < this.children.length; index++) {
  54026. this.children[index]._actionManager = this._actionManager;
  54027. this.children[index]._prepare();
  54028. }
  54029. };
  54030. CombineAction.prototype.execute = function (evt) {
  54031. for (var index = 0; index < this.children.length; index++) {
  54032. this.children[index].execute(evt);
  54033. }
  54034. };
  54035. CombineAction.prototype.serialize = function (parent) {
  54036. var serializationObject = _super.prototype._serialize.call(this, {
  54037. name: "CombineAction",
  54038. properties: [],
  54039. combine: []
  54040. }, parent);
  54041. for (var i = 0; i < this.children.length; i++) {
  54042. serializationObject.combine.push(this.children[i].serialize(null));
  54043. }
  54044. return serializationObject;
  54045. };
  54046. return CombineAction;
  54047. }(BABYLON.Action));
  54048. BABYLON.CombineAction = CombineAction;
  54049. var ExecuteCodeAction = /** @class */ (function (_super) {
  54050. __extends(ExecuteCodeAction, _super);
  54051. function ExecuteCodeAction(triggerOptions, func, condition) {
  54052. var _this = _super.call(this, triggerOptions, condition) || this;
  54053. _this.func = func;
  54054. return _this;
  54055. }
  54056. ExecuteCodeAction.prototype.execute = function (evt) {
  54057. this.func(evt);
  54058. };
  54059. return ExecuteCodeAction;
  54060. }(BABYLON.Action));
  54061. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54062. var SetParentAction = /** @class */ (function (_super) {
  54063. __extends(SetParentAction, _super);
  54064. function SetParentAction(triggerOptions, target, parent, condition) {
  54065. var _this = _super.call(this, triggerOptions, condition) || this;
  54066. _this._target = target;
  54067. _this._parent = parent;
  54068. return _this;
  54069. }
  54070. SetParentAction.prototype._prepare = function () {
  54071. };
  54072. SetParentAction.prototype.execute = function () {
  54073. if (this._target.parent === this._parent) {
  54074. return;
  54075. }
  54076. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54077. invertParentWorldMatrix.invert();
  54078. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54079. this._target.parent = this._parent;
  54080. };
  54081. SetParentAction.prototype.serialize = function (parent) {
  54082. return _super.prototype._serialize.call(this, {
  54083. name: "SetParentAction",
  54084. properties: [
  54085. BABYLON.Action._GetTargetProperty(this._target),
  54086. BABYLON.Action._GetTargetProperty(this._parent),
  54087. ]
  54088. }, parent);
  54089. };
  54090. return SetParentAction;
  54091. }(BABYLON.Action));
  54092. BABYLON.SetParentAction = SetParentAction;
  54093. var PlaySoundAction = /** @class */ (function (_super) {
  54094. __extends(PlaySoundAction, _super);
  54095. function PlaySoundAction(triggerOptions, sound, condition) {
  54096. var _this = _super.call(this, triggerOptions, condition) || this;
  54097. _this._sound = sound;
  54098. return _this;
  54099. }
  54100. PlaySoundAction.prototype._prepare = function () {
  54101. };
  54102. PlaySoundAction.prototype.execute = function () {
  54103. if (this._sound !== undefined)
  54104. this._sound.play();
  54105. };
  54106. PlaySoundAction.prototype.serialize = function (parent) {
  54107. return _super.prototype._serialize.call(this, {
  54108. name: "PlaySoundAction",
  54109. properties: [{ name: "sound", value: this._sound.name }]
  54110. }, parent);
  54111. };
  54112. return PlaySoundAction;
  54113. }(BABYLON.Action));
  54114. BABYLON.PlaySoundAction = PlaySoundAction;
  54115. var StopSoundAction = /** @class */ (function (_super) {
  54116. __extends(StopSoundAction, _super);
  54117. function StopSoundAction(triggerOptions, sound, condition) {
  54118. var _this = _super.call(this, triggerOptions, condition) || this;
  54119. _this._sound = sound;
  54120. return _this;
  54121. }
  54122. StopSoundAction.prototype._prepare = function () {
  54123. };
  54124. StopSoundAction.prototype.execute = function () {
  54125. if (this._sound !== undefined)
  54126. this._sound.stop();
  54127. };
  54128. StopSoundAction.prototype.serialize = function (parent) {
  54129. return _super.prototype._serialize.call(this, {
  54130. name: "StopSoundAction",
  54131. properties: [{ name: "sound", value: this._sound.name }]
  54132. }, parent);
  54133. };
  54134. return StopSoundAction;
  54135. }(BABYLON.Action));
  54136. BABYLON.StopSoundAction = StopSoundAction;
  54137. })(BABYLON || (BABYLON = {}));
  54138. //# sourceMappingURL=babylon.directActions.js.map
  54139. var BABYLON;
  54140. (function (BABYLON) {
  54141. var SpriteManager = /** @class */ (function () {
  54142. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54143. if (epsilon === void 0) { epsilon = 0.01; }
  54144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54145. this.name = name;
  54146. this.sprites = new Array();
  54147. this.renderingGroupId = 0;
  54148. this.layerMask = 0x0FFFFFFF;
  54149. this.fogEnabled = true;
  54150. this.isPickable = false;
  54151. /**
  54152. * An event triggered when the manager is disposed.
  54153. */
  54154. this.onDisposeObservable = new BABYLON.Observable();
  54155. this._vertexBuffers = {};
  54156. this._capacity = capacity;
  54157. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54158. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54159. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54160. if (cellSize.width && cellSize.height) {
  54161. this.cellWidth = cellSize.width;
  54162. this.cellHeight = cellSize.height;
  54163. }
  54164. else if (cellSize !== undefined) {
  54165. this.cellWidth = cellSize;
  54166. this.cellHeight = cellSize;
  54167. }
  54168. else {
  54169. return;
  54170. }
  54171. this._epsilon = epsilon;
  54172. this._scene = scene;
  54173. this._scene.spriteManagers.push(this);
  54174. var indices = [];
  54175. var index = 0;
  54176. for (var count = 0; count < capacity; count++) {
  54177. indices.push(index);
  54178. indices.push(index + 1);
  54179. indices.push(index + 2);
  54180. indices.push(index);
  54181. indices.push(index + 2);
  54182. indices.push(index + 3);
  54183. index += 4;
  54184. }
  54185. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54186. // VBO
  54187. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54188. this._vertexData = new Float32Array(capacity * 16 * 4);
  54189. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54190. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54191. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54192. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54193. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54195. this._vertexBuffers["options"] = options;
  54196. this._vertexBuffers["cellInfo"] = cellInfo;
  54197. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54198. // Effects
  54199. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54200. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54201. }
  54202. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54203. set: function (callback) {
  54204. if (this._onDisposeObserver) {
  54205. this.onDisposeObservable.remove(this._onDisposeObserver);
  54206. }
  54207. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54208. },
  54209. enumerable: true,
  54210. configurable: true
  54211. });
  54212. Object.defineProperty(SpriteManager.prototype, "texture", {
  54213. get: function () {
  54214. return this._spriteTexture;
  54215. },
  54216. set: function (value) {
  54217. this._spriteTexture = value;
  54218. },
  54219. enumerable: true,
  54220. configurable: true
  54221. });
  54222. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54223. var arrayOffset = index * 16;
  54224. if (offsetX === 0)
  54225. offsetX = this._epsilon;
  54226. else if (offsetX === 1)
  54227. offsetX = 1 - this._epsilon;
  54228. if (offsetY === 0)
  54229. offsetY = this._epsilon;
  54230. else if (offsetY === 1)
  54231. offsetY = 1 - this._epsilon;
  54232. this._vertexData[arrayOffset] = sprite.position.x;
  54233. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54234. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54235. this._vertexData[arrayOffset + 3] = sprite.angle;
  54236. this._vertexData[arrayOffset + 4] = sprite.width;
  54237. this._vertexData[arrayOffset + 5] = sprite.height;
  54238. this._vertexData[arrayOffset + 6] = offsetX;
  54239. this._vertexData[arrayOffset + 7] = offsetY;
  54240. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54241. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54242. var offset = (sprite.cellIndex / rowSize) >> 0;
  54243. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54244. this._vertexData[arrayOffset + 11] = offset;
  54245. // Color
  54246. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54247. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54248. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54249. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54250. };
  54251. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54252. var count = Math.min(this._capacity, this.sprites.length);
  54253. var min = BABYLON.Vector3.Zero();
  54254. var max = BABYLON.Vector3.Zero();
  54255. var distance = Number.MAX_VALUE;
  54256. var currentSprite = null;
  54257. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54258. var cameraView = camera.getViewMatrix();
  54259. for (var index = 0; index < count; index++) {
  54260. var sprite = this.sprites[index];
  54261. if (!sprite) {
  54262. continue;
  54263. }
  54264. if (predicate) {
  54265. if (!predicate(sprite)) {
  54266. continue;
  54267. }
  54268. }
  54269. else if (!sprite.isPickable) {
  54270. continue;
  54271. }
  54272. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54273. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54274. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54275. if (ray.intersectsBoxMinMax(min, max)) {
  54276. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54277. if (distance > currentDistance) {
  54278. distance = currentDistance;
  54279. currentSprite = sprite;
  54280. if (fastCheck) {
  54281. break;
  54282. }
  54283. }
  54284. }
  54285. }
  54286. if (currentSprite) {
  54287. var result = new BABYLON.PickingInfo();
  54288. result.hit = true;
  54289. result.pickedSprite = currentSprite;
  54290. result.distance = distance;
  54291. return result;
  54292. }
  54293. return null;
  54294. };
  54295. SpriteManager.prototype.render = function () {
  54296. // Check
  54297. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54298. return;
  54299. var engine = this._scene.getEngine();
  54300. var baseSize = this._spriteTexture.getBaseSize();
  54301. // Sprites
  54302. var deltaTime = engine.getDeltaTime();
  54303. var max = Math.min(this._capacity, this.sprites.length);
  54304. var rowSize = baseSize.width / this.cellWidth;
  54305. var offset = 0;
  54306. for (var index = 0; index < max; index++) {
  54307. var sprite = this.sprites[index];
  54308. if (!sprite) {
  54309. continue;
  54310. }
  54311. sprite._animate(deltaTime);
  54312. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54313. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54314. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54315. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54316. }
  54317. this._buffer.update(this._vertexData);
  54318. // Render
  54319. var effect = this._effectBase;
  54320. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54321. effect = this._effectFog;
  54322. }
  54323. engine.enableEffect(effect);
  54324. var viewMatrix = this._scene.getViewMatrix();
  54325. effect.setTexture("diffuseSampler", this._spriteTexture);
  54326. effect.setMatrix("view", viewMatrix);
  54327. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54328. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54329. // Fog
  54330. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54331. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54332. effect.setColor3("vFogColor", this._scene.fogColor);
  54333. }
  54334. // VBOs
  54335. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54336. // Draw order
  54337. engine.setDepthFunctionToLessOrEqual();
  54338. effect.setBool("alphaTest", true);
  54339. engine.setColorWrite(false);
  54340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54341. engine.setColorWrite(true);
  54342. effect.setBool("alphaTest", false);
  54343. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54344. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54345. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54346. };
  54347. SpriteManager.prototype.dispose = function () {
  54348. if (this._buffer) {
  54349. this._buffer.dispose();
  54350. this._buffer = null;
  54351. }
  54352. if (this._indexBuffer) {
  54353. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54354. this._indexBuffer = null;
  54355. }
  54356. if (this._spriteTexture) {
  54357. this._spriteTexture.dispose();
  54358. this._spriteTexture = null;
  54359. }
  54360. // Remove from scene
  54361. var index = this._scene.spriteManagers.indexOf(this);
  54362. this._scene.spriteManagers.splice(index, 1);
  54363. // Callback
  54364. this.onDisposeObservable.notifyObservers(this);
  54365. this.onDisposeObservable.clear();
  54366. };
  54367. return SpriteManager;
  54368. }());
  54369. BABYLON.SpriteManager = SpriteManager;
  54370. })(BABYLON || (BABYLON = {}));
  54371. //# sourceMappingURL=babylon.spriteManager.js.map
  54372. var BABYLON;
  54373. (function (BABYLON) {
  54374. var Sprite = /** @class */ (function () {
  54375. function Sprite(name, manager) {
  54376. this.name = name;
  54377. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54378. this.width = 1.0;
  54379. this.height = 1.0;
  54380. this.angle = 0;
  54381. this.cellIndex = 0;
  54382. this.invertU = 0;
  54383. this.invertV = 0;
  54384. this.animations = new Array();
  54385. this.isPickable = false;
  54386. this._animationStarted = false;
  54387. this._loopAnimation = false;
  54388. this._fromIndex = 0;
  54389. this._toIndex = 0;
  54390. this._delay = 0;
  54391. this._direction = 1;
  54392. this._time = 0;
  54393. this._manager = manager;
  54394. this._manager.sprites.push(this);
  54395. this.position = BABYLON.Vector3.Zero();
  54396. }
  54397. Object.defineProperty(Sprite.prototype, "size", {
  54398. get: function () {
  54399. return this.width;
  54400. },
  54401. set: function (value) {
  54402. this.width = value;
  54403. this.height = value;
  54404. },
  54405. enumerable: true,
  54406. configurable: true
  54407. });
  54408. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54409. this._fromIndex = from;
  54410. this._toIndex = to;
  54411. this._loopAnimation = loop;
  54412. this._delay = delay;
  54413. this._animationStarted = true;
  54414. this._direction = from < to ? 1 : -1;
  54415. this.cellIndex = from;
  54416. this._time = 0;
  54417. this._onAnimationEnd = onAnimationEnd;
  54418. };
  54419. Sprite.prototype.stopAnimation = function () {
  54420. this._animationStarted = false;
  54421. };
  54422. Sprite.prototype._animate = function (deltaTime) {
  54423. if (!this._animationStarted)
  54424. return;
  54425. this._time += deltaTime;
  54426. if (this._time > this._delay) {
  54427. this._time = this._time % this._delay;
  54428. this.cellIndex += this._direction;
  54429. if (this.cellIndex > this._toIndex) {
  54430. if (this._loopAnimation) {
  54431. this.cellIndex = this._fromIndex;
  54432. }
  54433. else {
  54434. this.cellIndex = this._toIndex;
  54435. this._animationStarted = false;
  54436. if (this._onAnimationEnd) {
  54437. this._onAnimationEnd();
  54438. }
  54439. if (this.disposeWhenFinishedAnimating) {
  54440. this.dispose();
  54441. }
  54442. }
  54443. }
  54444. }
  54445. };
  54446. Sprite.prototype.dispose = function () {
  54447. for (var i = 0; i < this._manager.sprites.length; i++) {
  54448. if (this._manager.sprites[i] == this) {
  54449. this._manager.sprites.splice(i, 1);
  54450. }
  54451. }
  54452. };
  54453. return Sprite;
  54454. }());
  54455. BABYLON.Sprite = Sprite;
  54456. })(BABYLON || (BABYLON = {}));
  54457. //# sourceMappingURL=babylon.sprite.js.map
  54458. var BABYLON;
  54459. (function (BABYLON) {
  54460. var IntersectionInfo = /** @class */ (function () {
  54461. function IntersectionInfo(bu, bv, distance) {
  54462. this.bu = bu;
  54463. this.bv = bv;
  54464. this.distance = distance;
  54465. this.faceId = 0;
  54466. this.subMeshId = 0;
  54467. }
  54468. return IntersectionInfo;
  54469. }());
  54470. BABYLON.IntersectionInfo = IntersectionInfo;
  54471. var PickingInfo = /** @class */ (function () {
  54472. function PickingInfo() {
  54473. this.hit = false;
  54474. this.distance = 0;
  54475. this.pickedPoint = null;
  54476. this.pickedMesh = null;
  54477. this.bu = 0;
  54478. this.bv = 0;
  54479. this.faceId = -1;
  54480. this.subMeshId = 0;
  54481. this.pickedSprite = null;
  54482. }
  54483. // Methods
  54484. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54485. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54486. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54487. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54488. return null;
  54489. }
  54490. var indices = this.pickedMesh.getIndices();
  54491. if (!indices) {
  54492. return null;
  54493. }
  54494. var result;
  54495. if (useVerticesNormals) {
  54496. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54497. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54498. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54499. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54500. normal0 = normal0.scale(this.bu);
  54501. normal1 = normal1.scale(this.bv);
  54502. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54503. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54504. }
  54505. else {
  54506. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54507. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54508. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54509. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54510. var p1p2 = vertex1.subtract(vertex2);
  54511. var p3p2 = vertex3.subtract(vertex2);
  54512. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54513. }
  54514. if (useWorldCoordinates) {
  54515. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54516. }
  54517. return BABYLON.Vector3.Normalize(result);
  54518. };
  54519. PickingInfo.prototype.getTextureCoordinates = function () {
  54520. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54521. return null;
  54522. }
  54523. var indices = this.pickedMesh.getIndices();
  54524. if (!indices) {
  54525. return null;
  54526. }
  54527. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54528. if (!uvs) {
  54529. return null;
  54530. }
  54531. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54532. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54533. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54534. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54535. uv1 = uv1.scale(this.bu);
  54536. uv2 = uv2.scale(this.bv);
  54537. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54538. };
  54539. return PickingInfo;
  54540. }());
  54541. BABYLON.PickingInfo = PickingInfo;
  54542. })(BABYLON || (BABYLON = {}));
  54543. //# sourceMappingURL=babylon.pickingInfo.js.map
  54544. var BABYLON;
  54545. (function (BABYLON) {
  54546. var Ray = /** @class */ (function () {
  54547. function Ray(origin, direction, length) {
  54548. if (length === void 0) { length = Number.MAX_VALUE; }
  54549. this.origin = origin;
  54550. this.direction = direction;
  54551. this.length = length;
  54552. }
  54553. // Methods
  54554. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54555. var d = 0.0;
  54556. var maxValue = Number.MAX_VALUE;
  54557. var inv;
  54558. var min;
  54559. var max;
  54560. var temp;
  54561. if (Math.abs(this.direction.x) < 0.0000001) {
  54562. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54563. return false;
  54564. }
  54565. }
  54566. else {
  54567. inv = 1.0 / this.direction.x;
  54568. min = (minimum.x - this.origin.x) * inv;
  54569. max = (maximum.x - this.origin.x) * inv;
  54570. if (max === -Infinity) {
  54571. max = Infinity;
  54572. }
  54573. if (min > max) {
  54574. temp = min;
  54575. min = max;
  54576. max = temp;
  54577. }
  54578. d = Math.max(min, d);
  54579. maxValue = Math.min(max, maxValue);
  54580. if (d > maxValue) {
  54581. return false;
  54582. }
  54583. }
  54584. if (Math.abs(this.direction.y) < 0.0000001) {
  54585. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54586. return false;
  54587. }
  54588. }
  54589. else {
  54590. inv = 1.0 / this.direction.y;
  54591. min = (minimum.y - this.origin.y) * inv;
  54592. max = (maximum.y - this.origin.y) * inv;
  54593. if (max === -Infinity) {
  54594. max = Infinity;
  54595. }
  54596. if (min > max) {
  54597. temp = min;
  54598. min = max;
  54599. max = temp;
  54600. }
  54601. d = Math.max(min, d);
  54602. maxValue = Math.min(max, maxValue);
  54603. if (d > maxValue) {
  54604. return false;
  54605. }
  54606. }
  54607. if (Math.abs(this.direction.z) < 0.0000001) {
  54608. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54609. return false;
  54610. }
  54611. }
  54612. else {
  54613. inv = 1.0 / this.direction.z;
  54614. min = (minimum.z - this.origin.z) * inv;
  54615. max = (maximum.z - this.origin.z) * inv;
  54616. if (max === -Infinity) {
  54617. max = Infinity;
  54618. }
  54619. if (min > max) {
  54620. temp = min;
  54621. min = max;
  54622. max = temp;
  54623. }
  54624. d = Math.max(min, d);
  54625. maxValue = Math.min(max, maxValue);
  54626. if (d > maxValue) {
  54627. return false;
  54628. }
  54629. }
  54630. return true;
  54631. };
  54632. Ray.prototype.intersectsBox = function (box) {
  54633. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54634. };
  54635. Ray.prototype.intersectsSphere = function (sphere) {
  54636. var x = sphere.center.x - this.origin.x;
  54637. var y = sphere.center.y - this.origin.y;
  54638. var z = sphere.center.z - this.origin.z;
  54639. var pyth = (x * x) + (y * y) + (z * z);
  54640. var rr = sphere.radius * sphere.radius;
  54641. if (pyth <= rr) {
  54642. return true;
  54643. }
  54644. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54645. if (dot < 0.0) {
  54646. return false;
  54647. }
  54648. var temp = pyth - (dot * dot);
  54649. return temp <= rr;
  54650. };
  54651. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54652. if (!this._edge1) {
  54653. this._edge1 = BABYLON.Vector3.Zero();
  54654. this._edge2 = BABYLON.Vector3.Zero();
  54655. this._pvec = BABYLON.Vector3.Zero();
  54656. this._tvec = BABYLON.Vector3.Zero();
  54657. this._qvec = BABYLON.Vector3.Zero();
  54658. }
  54659. vertex1.subtractToRef(vertex0, this._edge1);
  54660. vertex2.subtractToRef(vertex0, this._edge2);
  54661. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54662. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54663. if (det === 0) {
  54664. return null;
  54665. }
  54666. var invdet = 1 / det;
  54667. this.origin.subtractToRef(vertex0, this._tvec);
  54668. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54669. if (bu < 0 || bu > 1.0) {
  54670. return null;
  54671. }
  54672. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54673. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54674. if (bv < 0 || bu + bv > 1.0) {
  54675. return null;
  54676. }
  54677. //check if the distance is longer than the predefined length.
  54678. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54679. if (distance > this.length) {
  54680. return null;
  54681. }
  54682. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54683. };
  54684. Ray.prototype.intersectsPlane = function (plane) {
  54685. var distance;
  54686. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54687. if (Math.abs(result1) < 9.99999997475243E-07) {
  54688. return null;
  54689. }
  54690. else {
  54691. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54692. distance = (-plane.d - result2) / result1;
  54693. if (distance < 0.0) {
  54694. if (distance < -9.99999997475243E-07) {
  54695. return null;
  54696. }
  54697. else {
  54698. return 0;
  54699. }
  54700. }
  54701. return distance;
  54702. }
  54703. };
  54704. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54705. var tm = BABYLON.Tmp.Matrix[0];
  54706. mesh.getWorldMatrix().invertToRef(tm);
  54707. if (this._tmpRay) {
  54708. Ray.TransformToRef(this, tm, this._tmpRay);
  54709. }
  54710. else {
  54711. this._tmpRay = Ray.Transform(this, tm);
  54712. }
  54713. return mesh.intersects(this._tmpRay, fastCheck);
  54714. };
  54715. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54716. if (results) {
  54717. results.length = 0;
  54718. }
  54719. else {
  54720. results = [];
  54721. }
  54722. for (var i = 0; i < meshes.length; i++) {
  54723. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54724. if (pickInfo.hit) {
  54725. results.push(pickInfo);
  54726. }
  54727. }
  54728. results.sort(this._comparePickingInfo);
  54729. return results;
  54730. };
  54731. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54732. if (pickingInfoA.distance < pickingInfoB.distance) {
  54733. return -1;
  54734. }
  54735. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54736. return 1;
  54737. }
  54738. else {
  54739. return 0;
  54740. }
  54741. };
  54742. /**
  54743. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54744. * @param sega the first point of the segment to test the intersection against
  54745. * @param segb the second point of the segment to test the intersection against
  54746. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54747. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54748. */
  54749. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54750. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54751. var u = segb.subtract(sega);
  54752. var v = rsegb.subtract(this.origin);
  54753. var w = sega.subtract(this.origin);
  54754. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54755. var b = BABYLON.Vector3.Dot(u, v);
  54756. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54757. var d = BABYLON.Vector3.Dot(u, w);
  54758. var e = BABYLON.Vector3.Dot(v, w);
  54759. var D = a * c - b * b; // always >= 0
  54760. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54761. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54762. // compute the line parameters of the two closest points
  54763. if (D < Ray.smallnum) { // the lines are almost parallel
  54764. sN = 0.0; // force using point P0 on segment S1
  54765. sD = 1.0; // to prevent possible division by 0.0 later
  54766. tN = e;
  54767. tD = c;
  54768. }
  54769. else { // get the closest points on the infinite lines
  54770. sN = (b * e - c * d);
  54771. tN = (a * e - b * d);
  54772. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54773. sN = 0.0;
  54774. tN = e;
  54775. tD = c;
  54776. }
  54777. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54778. sN = sD;
  54779. tN = e + b;
  54780. tD = c;
  54781. }
  54782. }
  54783. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54784. tN = 0.0;
  54785. // recompute sc for this edge
  54786. if (-d < 0.0) {
  54787. sN = 0.0;
  54788. }
  54789. else if (-d > a)
  54790. sN = sD;
  54791. else {
  54792. sN = -d;
  54793. sD = a;
  54794. }
  54795. }
  54796. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54797. tN = tD;
  54798. // recompute sc for this edge
  54799. if ((-d + b) < 0.0) {
  54800. sN = 0;
  54801. }
  54802. else if ((-d + b) > a) {
  54803. sN = sD;
  54804. }
  54805. else {
  54806. sN = (-d + b);
  54807. sD = a;
  54808. }
  54809. }
  54810. // finally do the division to get sc and tc
  54811. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54812. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54813. // get the difference of the two closest points
  54814. var qtc = v.multiplyByFloats(tc, tc, tc);
  54815. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54816. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54817. if (isIntersected) {
  54818. return qtc.length();
  54819. }
  54820. return -1;
  54821. };
  54822. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54823. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54824. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54825. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54826. this.direction.normalize();
  54827. return this;
  54828. };
  54829. // Statics
  54830. Ray.Zero = function () {
  54831. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54832. };
  54833. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54834. var result = Ray.Zero();
  54835. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54836. };
  54837. /**
  54838. * 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
  54839. * transformed to the given world matrix.
  54840. * @param origin The origin point
  54841. * @param end The end point
  54842. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54843. */
  54844. Ray.CreateNewFromTo = function (origin, end, world) {
  54845. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54846. var direction = end.subtract(origin);
  54847. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54848. direction.normalize();
  54849. return Ray.Transform(new Ray(origin, direction, length), world);
  54850. };
  54851. Ray.Transform = function (ray, matrix) {
  54852. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54853. Ray.TransformToRef(ray, matrix, result);
  54854. return result;
  54855. };
  54856. Ray.TransformToRef = function (ray, matrix, result) {
  54857. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54858. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54859. result.length = ray.length;
  54860. var dir = result.direction;
  54861. var len = dir.length();
  54862. if (!(len === 0 || len === 1)) {
  54863. var num = 1.0 / len;
  54864. dir.x *= num;
  54865. dir.y *= num;
  54866. dir.z *= num;
  54867. result.length *= len;
  54868. }
  54869. };
  54870. Ray.smallnum = 0.00000001;
  54871. Ray.rayl = 10e8;
  54872. return Ray;
  54873. }());
  54874. BABYLON.Ray = Ray;
  54875. })(BABYLON || (BABYLON = {}));
  54876. //# sourceMappingURL=babylon.ray.js.map
  54877. var BABYLON;
  54878. (function (BABYLON) {
  54879. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54880. if (boxMin.x > sphereCenter.x + sphereRadius)
  54881. return false;
  54882. if (sphereCenter.x - sphereRadius > boxMax.x)
  54883. return false;
  54884. if (boxMin.y > sphereCenter.y + sphereRadius)
  54885. return false;
  54886. if (sphereCenter.y - sphereRadius > boxMax.y)
  54887. return false;
  54888. if (boxMin.z > sphereCenter.z + sphereRadius)
  54889. return false;
  54890. if (sphereCenter.z - sphereRadius > boxMax.z)
  54891. return false;
  54892. return true;
  54893. };
  54894. var getLowestRoot = (function () {
  54895. var result = { root: 0, found: false };
  54896. return function (a, b, c, maxR) {
  54897. result.root = 0;
  54898. result.found = false;
  54899. var determinant = b * b - 4.0 * a * c;
  54900. if (determinant < 0)
  54901. return result;
  54902. var sqrtD = Math.sqrt(determinant);
  54903. var r1 = (-b - sqrtD) / (2.0 * a);
  54904. var r2 = (-b + sqrtD) / (2.0 * a);
  54905. if (r1 > r2) {
  54906. var temp = r2;
  54907. r2 = r1;
  54908. r1 = temp;
  54909. }
  54910. if (r1 > 0 && r1 < maxR) {
  54911. result.root = r1;
  54912. result.found = true;
  54913. return result;
  54914. }
  54915. if (r2 > 0 && r2 < maxR) {
  54916. result.root = r2;
  54917. result.found = true;
  54918. return result;
  54919. }
  54920. return result;
  54921. };
  54922. })();
  54923. var Collider = /** @class */ (function () {
  54924. function Collider() {
  54925. this._collisionPoint = BABYLON.Vector3.Zero();
  54926. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54927. this._tempVector = BABYLON.Vector3.Zero();
  54928. this._tempVector2 = BABYLON.Vector3.Zero();
  54929. this._tempVector3 = BABYLON.Vector3.Zero();
  54930. this._tempVector4 = BABYLON.Vector3.Zero();
  54931. this._edge = BABYLON.Vector3.Zero();
  54932. this._baseToVertex = BABYLON.Vector3.Zero();
  54933. this._destinationPoint = BABYLON.Vector3.Zero();
  54934. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54935. this._displacementVector = BABYLON.Vector3.Zero();
  54936. this._radius = BABYLON.Vector3.One();
  54937. this._retry = 0;
  54938. this._basePointWorld = BABYLON.Vector3.Zero();
  54939. this._velocityWorld = BABYLON.Vector3.Zero();
  54940. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54941. this._collisionMask = -1;
  54942. }
  54943. Object.defineProperty(Collider.prototype, "collisionMask", {
  54944. get: function () {
  54945. return this._collisionMask;
  54946. },
  54947. set: function (mask) {
  54948. this._collisionMask = !isNaN(mask) ? mask : -1;
  54949. },
  54950. enumerable: true,
  54951. configurable: true
  54952. });
  54953. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54954. /**
  54955. * Gets the plane normal used to compute the sliding response (in local space)
  54956. */
  54957. get: function () {
  54958. return this._slidePlaneNormal;
  54959. },
  54960. enumerable: true,
  54961. configurable: true
  54962. });
  54963. // Methods
  54964. Collider.prototype._initialize = function (source, dir, e) {
  54965. this._velocity = dir;
  54966. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54967. this._basePoint = source;
  54968. source.multiplyToRef(this._radius, this._basePointWorld);
  54969. dir.multiplyToRef(this._radius, this._velocityWorld);
  54970. this._velocityWorldLength = this._velocityWorld.length();
  54971. this._epsilon = e;
  54972. this.collisionFound = false;
  54973. };
  54974. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54975. pa.subtractToRef(point, this._tempVector);
  54976. pb.subtractToRef(point, this._tempVector2);
  54977. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54978. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54979. if (d < 0)
  54980. return false;
  54981. pc.subtractToRef(point, this._tempVector3);
  54982. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54983. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54984. if (d < 0)
  54985. return false;
  54986. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54987. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54988. return d >= 0;
  54989. };
  54990. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54991. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54992. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54993. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54994. return false;
  54995. }
  54996. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54997. return false;
  54998. return true;
  54999. };
  55000. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55001. var t0;
  55002. var embeddedInPlane = false;
  55003. //defensive programming, actually not needed.
  55004. if (!trianglePlaneArray) {
  55005. trianglePlaneArray = [];
  55006. }
  55007. if (!trianglePlaneArray[faceIndex]) {
  55008. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55009. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55010. }
  55011. var trianglePlane = trianglePlaneArray[faceIndex];
  55012. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55013. return;
  55014. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55015. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55016. if (normalDotVelocity == 0) {
  55017. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55018. return;
  55019. embeddedInPlane = true;
  55020. t0 = 0;
  55021. }
  55022. else {
  55023. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55024. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55025. if (t0 > t1) {
  55026. var temp = t1;
  55027. t1 = t0;
  55028. t0 = temp;
  55029. }
  55030. if (t0 > 1.0 || t1 < 0.0)
  55031. return;
  55032. if (t0 < 0)
  55033. t0 = 0;
  55034. if (t0 > 1.0)
  55035. t0 = 1.0;
  55036. }
  55037. this._collisionPoint.copyFromFloats(0, 0, 0);
  55038. var found = false;
  55039. var t = 1.0;
  55040. if (!embeddedInPlane) {
  55041. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55042. this._velocity.scaleToRef(t0, this._tempVector);
  55043. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55044. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55045. found = true;
  55046. t = t0;
  55047. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55048. }
  55049. }
  55050. if (!found) {
  55051. var velocitySquaredLength = this._velocity.lengthSquared();
  55052. var a = velocitySquaredLength;
  55053. this._basePoint.subtractToRef(p1, this._tempVector);
  55054. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55055. var c = this._tempVector.lengthSquared() - 1.0;
  55056. var lowestRoot = getLowestRoot(a, b, c, t);
  55057. if (lowestRoot.found) {
  55058. t = lowestRoot.root;
  55059. found = true;
  55060. this._collisionPoint.copyFrom(p1);
  55061. }
  55062. this._basePoint.subtractToRef(p2, this._tempVector);
  55063. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55064. c = this._tempVector.lengthSquared() - 1.0;
  55065. lowestRoot = getLowestRoot(a, b, c, t);
  55066. if (lowestRoot.found) {
  55067. t = lowestRoot.root;
  55068. found = true;
  55069. this._collisionPoint.copyFrom(p2);
  55070. }
  55071. this._basePoint.subtractToRef(p3, this._tempVector);
  55072. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55073. c = this._tempVector.lengthSquared() - 1.0;
  55074. lowestRoot = getLowestRoot(a, b, c, t);
  55075. if (lowestRoot.found) {
  55076. t = lowestRoot.root;
  55077. found = true;
  55078. this._collisionPoint.copyFrom(p3);
  55079. }
  55080. p2.subtractToRef(p1, this._edge);
  55081. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55082. var edgeSquaredLength = this._edge.lengthSquared();
  55083. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55084. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55085. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55086. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55087. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55088. lowestRoot = getLowestRoot(a, b, c, t);
  55089. if (lowestRoot.found) {
  55090. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55091. if (f >= 0.0 && f <= 1.0) {
  55092. t = lowestRoot.root;
  55093. found = true;
  55094. this._edge.scaleInPlace(f);
  55095. p1.addToRef(this._edge, this._collisionPoint);
  55096. }
  55097. }
  55098. p3.subtractToRef(p2, this._edge);
  55099. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55100. edgeSquaredLength = this._edge.lengthSquared();
  55101. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55102. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55103. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55104. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55105. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55106. lowestRoot = getLowestRoot(a, b, c, t);
  55107. if (lowestRoot.found) {
  55108. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55109. if (f >= 0.0 && f <= 1.0) {
  55110. t = lowestRoot.root;
  55111. found = true;
  55112. this._edge.scaleInPlace(f);
  55113. p2.addToRef(this._edge, this._collisionPoint);
  55114. }
  55115. }
  55116. p1.subtractToRef(p3, this._edge);
  55117. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55118. edgeSquaredLength = this._edge.lengthSquared();
  55119. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55120. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55121. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55122. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55123. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55124. lowestRoot = getLowestRoot(a, b, c, t);
  55125. if (lowestRoot.found) {
  55126. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55127. if (f >= 0.0 && f <= 1.0) {
  55128. t = lowestRoot.root;
  55129. found = true;
  55130. this._edge.scaleInPlace(f);
  55131. p3.addToRef(this._edge, this._collisionPoint);
  55132. }
  55133. }
  55134. }
  55135. if (found) {
  55136. var distToCollision = t * this._velocity.length();
  55137. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55138. if (!this.intersectionPoint) {
  55139. this.intersectionPoint = this._collisionPoint.clone();
  55140. }
  55141. else {
  55142. this.intersectionPoint.copyFrom(this._collisionPoint);
  55143. }
  55144. this._nearestDistance = distToCollision;
  55145. this.collisionFound = true;
  55146. }
  55147. }
  55148. };
  55149. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55150. for (var i = indexStart; i < indexEnd; i += 3) {
  55151. var p1 = pts[indices[i] - decal];
  55152. var p2 = pts[indices[i + 1] - decal];
  55153. var p3 = pts[indices[i + 2] - decal];
  55154. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55155. }
  55156. };
  55157. Collider.prototype._getResponse = function (pos, vel) {
  55158. pos.addToRef(vel, this._destinationPoint);
  55159. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55160. this._basePoint.addToRef(vel, pos);
  55161. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55162. this._slidePlaneNormal.normalize();
  55163. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55164. pos.addInPlace(this._displacementVector);
  55165. this.intersectionPoint.addInPlace(this._displacementVector);
  55166. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55167. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55168. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55169. };
  55170. return Collider;
  55171. }());
  55172. BABYLON.Collider = Collider;
  55173. })(BABYLON || (BABYLON = {}));
  55174. //# sourceMappingURL=babylon.collider.js.map
  55175. var BABYLON;
  55176. (function (BABYLON) {
  55177. //WebWorker code will be inserted to this variable.
  55178. BABYLON.CollisionWorker = "";
  55179. /** Defines supported task for worker process */
  55180. var WorkerTaskType;
  55181. (function (WorkerTaskType) {
  55182. /** Initialization */
  55183. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55184. /** Update of geometry */
  55185. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55186. /** Evaluate collision */
  55187. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55188. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55189. /** Defines kind of replies returned by worker */
  55190. var WorkerReplyType;
  55191. (function (WorkerReplyType) {
  55192. /** Success */
  55193. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55194. /** Unkown error */
  55195. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55196. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55197. var CollisionCoordinatorWorker = /** @class */ (function () {
  55198. function CollisionCoordinatorWorker() {
  55199. var _this = this;
  55200. this._scaledPosition = BABYLON.Vector3.Zero();
  55201. this._scaledVelocity = BABYLON.Vector3.Zero();
  55202. this.onMeshUpdated = function (transformNode) {
  55203. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55204. };
  55205. this.onGeometryUpdated = function (geometry) {
  55206. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55207. };
  55208. this._afterRender = function () {
  55209. if (!_this._init)
  55210. return;
  55211. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55212. return;
  55213. }
  55214. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55215. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55216. if (_this._runningUpdated > 4) {
  55217. return;
  55218. }
  55219. ++_this._runningUpdated;
  55220. var payload = {
  55221. updatedMeshes: _this._addUpdateMeshesList,
  55222. updatedGeometries: _this._addUpdateGeometriesList,
  55223. removedGeometries: _this._toRemoveGeometryArray,
  55224. removedMeshes: _this._toRemoveMeshesArray
  55225. };
  55226. var message = {
  55227. payload: payload,
  55228. taskType: WorkerTaskType.UPDATE
  55229. };
  55230. var serializable = [];
  55231. for (var id in payload.updatedGeometries) {
  55232. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55233. //prepare transferables
  55234. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55235. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55236. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55237. }
  55238. }
  55239. _this._worker.postMessage(message, serializable);
  55240. _this._addUpdateMeshesList = {};
  55241. _this._addUpdateGeometriesList = {};
  55242. _this._toRemoveGeometryArray = [];
  55243. _this._toRemoveMeshesArray = [];
  55244. };
  55245. this._onMessageFromWorker = function (e) {
  55246. var returnData = e.data;
  55247. if (returnData.error != WorkerReplyType.SUCCESS) {
  55248. //TODO what errors can be returned from the worker?
  55249. BABYLON.Tools.Warn("error returned from worker!");
  55250. return;
  55251. }
  55252. switch (returnData.taskType) {
  55253. case WorkerTaskType.INIT:
  55254. _this._init = true;
  55255. //Update the worked with ALL of the scene's current state
  55256. _this._scene.meshes.forEach(function (mesh) {
  55257. _this.onMeshAdded(mesh);
  55258. });
  55259. _this._scene.getGeometries().forEach(function (geometry) {
  55260. _this.onGeometryAdded(geometry);
  55261. });
  55262. break;
  55263. case WorkerTaskType.UPDATE:
  55264. _this._runningUpdated--;
  55265. break;
  55266. case WorkerTaskType.COLLIDE:
  55267. var returnPayload = returnData.payload;
  55268. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55269. return;
  55270. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55271. if (callback) {
  55272. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55273. if (mesh) {
  55274. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55275. }
  55276. }
  55277. //cleanup
  55278. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55279. break;
  55280. }
  55281. };
  55282. this._collisionsCallbackArray = [];
  55283. this._init = false;
  55284. this._runningUpdated = 0;
  55285. this._addUpdateMeshesList = {};
  55286. this._addUpdateGeometriesList = {};
  55287. this._toRemoveGeometryArray = [];
  55288. this._toRemoveMeshesArray = [];
  55289. }
  55290. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55291. if (!this._init)
  55292. return;
  55293. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55294. return;
  55295. position.divideToRef(collider._radius, this._scaledPosition);
  55296. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55297. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55298. var payload = {
  55299. collider: {
  55300. position: this._scaledPosition.asArray(),
  55301. velocity: this._scaledVelocity.asArray(),
  55302. radius: collider._radius.asArray()
  55303. },
  55304. collisionId: collisionIndex,
  55305. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55306. maximumRetry: maximumRetry
  55307. };
  55308. var message = {
  55309. payload: payload,
  55310. taskType: WorkerTaskType.COLLIDE
  55311. };
  55312. this._worker.postMessage(message);
  55313. };
  55314. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55315. this._scene = scene;
  55316. this._scene.registerAfterRender(this._afterRender);
  55317. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55318. this._worker = new Worker(workerUrl);
  55319. this._worker.onmessage = this._onMessageFromWorker;
  55320. var message = {
  55321. payload: {},
  55322. taskType: WorkerTaskType.INIT
  55323. };
  55324. this._worker.postMessage(message);
  55325. };
  55326. CollisionCoordinatorWorker.prototype.destroy = function () {
  55327. this._scene.unregisterAfterRender(this._afterRender);
  55328. this._worker.terminate();
  55329. };
  55330. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55331. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55332. this.onMeshUpdated(mesh);
  55333. };
  55334. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55335. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55336. };
  55337. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55338. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55339. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55340. this.onGeometryUpdated(geometry);
  55341. };
  55342. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55343. this._toRemoveGeometryArray.push(geometry.id);
  55344. };
  55345. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55346. var submeshes = [];
  55347. if (mesh.subMeshes) {
  55348. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55349. var boundingInfo = sm.getBoundingInfo();
  55350. return {
  55351. position: idx,
  55352. verticesStart: sm.verticesStart,
  55353. verticesCount: sm.verticesCount,
  55354. indexStart: sm.indexStart,
  55355. indexCount: sm.indexCount,
  55356. hasMaterial: !!sm.getMaterial(),
  55357. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55358. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55359. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55360. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55361. };
  55362. });
  55363. }
  55364. var geometryId = null;
  55365. if (mesh instanceof BABYLON.Mesh) {
  55366. var geometry = mesh.geometry;
  55367. geometryId = geometry ? geometry.id : null;
  55368. }
  55369. else if (mesh instanceof BABYLON.InstancedMesh) {
  55370. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55371. geometryId = geometry ? geometry.id : null;
  55372. }
  55373. var boundingInfo = mesh.getBoundingInfo();
  55374. return {
  55375. uniqueId: mesh.uniqueId,
  55376. id: mesh.id,
  55377. name: mesh.name,
  55378. geometryId: geometryId,
  55379. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55380. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55381. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55382. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55383. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55384. subMeshes: submeshes,
  55385. checkCollisions: mesh.checkCollisions
  55386. };
  55387. };
  55388. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55389. return {
  55390. id: geometry.id,
  55391. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55392. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55393. indices: new Uint32Array(geometry.getIndices() || []),
  55394. };
  55395. };
  55396. return CollisionCoordinatorWorker;
  55397. }());
  55398. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55399. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55400. function CollisionCoordinatorLegacy() {
  55401. this._scaledPosition = BABYLON.Vector3.Zero();
  55402. this._scaledVelocity = BABYLON.Vector3.Zero();
  55403. this._finalPosition = BABYLON.Vector3.Zero();
  55404. }
  55405. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55406. position.divideToRef(collider._radius, this._scaledPosition);
  55407. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55408. collider.collidedMesh = null;
  55409. collider._retry = 0;
  55410. collider._initialVelocity = this._scaledVelocity;
  55411. collider._initialPosition = this._scaledPosition;
  55412. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55413. this._finalPosition.multiplyInPlace(collider._radius);
  55414. //run the callback
  55415. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55416. };
  55417. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55418. this._scene = scene;
  55419. };
  55420. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55421. //Legacy need no destruction method.
  55422. };
  55423. //No update in legacy mode
  55424. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55425. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55426. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55427. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55428. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55429. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55430. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55431. if (excludedMesh === void 0) { excludedMesh = null; }
  55432. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55433. if (collider._retry >= maximumRetry) {
  55434. finalPosition.copyFrom(position);
  55435. return;
  55436. }
  55437. // Check if this is a mesh else camera or -1
  55438. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55439. collider._initialize(position, velocity, closeDistance);
  55440. // Check all meshes
  55441. for (var index = 0; index < this._scene.meshes.length; index++) {
  55442. var mesh = this._scene.meshes[index];
  55443. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55444. mesh._checkCollision(collider);
  55445. }
  55446. }
  55447. if (!collider.collisionFound) {
  55448. position.addToRef(velocity, finalPosition);
  55449. return;
  55450. }
  55451. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55452. collider._getResponse(position, velocity);
  55453. }
  55454. if (velocity.length() <= closeDistance) {
  55455. finalPosition.copyFrom(position);
  55456. return;
  55457. }
  55458. collider._retry++;
  55459. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55460. };
  55461. return CollisionCoordinatorLegacy;
  55462. }());
  55463. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55464. })(BABYLON || (BABYLON = {}));
  55465. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55466. var BABYLON;
  55467. (function (BABYLON) {
  55468. /**
  55469. * A particle represents one of the element emitted by a particle system.
  55470. * This is mainly define by its coordinates, direction, velocity and age.
  55471. */
  55472. var Particle = /** @class */ (function () {
  55473. /**
  55474. * Creates a new instance Particle
  55475. * @param particleSystem the particle system the particle belongs to
  55476. */
  55477. function Particle(
  55478. /**
  55479. * particleSystem the particle system the particle belongs to.
  55480. */
  55481. particleSystem) {
  55482. this.particleSystem = particleSystem;
  55483. /**
  55484. * The world position of the particle in the scene.
  55485. */
  55486. this.position = BABYLON.Vector3.Zero();
  55487. /**
  55488. * The world direction of the particle in the scene.
  55489. */
  55490. this.direction = BABYLON.Vector3.Zero();
  55491. /**
  55492. * The color of the particle.
  55493. */
  55494. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55495. /**
  55496. * The color change of the particle per step.
  55497. */
  55498. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55499. /**
  55500. * Defines how long will the life of the particle be.
  55501. */
  55502. this.lifeTime = 1.0;
  55503. /**
  55504. * The current age of the particle.
  55505. */
  55506. this.age = 0;
  55507. /**
  55508. * The current size of the particle.
  55509. */
  55510. this.size = 0;
  55511. /**
  55512. * The current angle of the particle.
  55513. */
  55514. this.angle = 0;
  55515. /**
  55516. * Defines how fast is the angle changing.
  55517. */
  55518. this.angularSpeed = 0;
  55519. /**
  55520. * Defines the cell index used by the particle to be rendered from a sprite.
  55521. */
  55522. this.cellIndex = 0;
  55523. this._currentFrameCounter = 0;
  55524. if (!this.particleSystem.isAnimationSheetEnabled) {
  55525. return;
  55526. }
  55527. this.updateCellInfoFromSystem();
  55528. }
  55529. Particle.prototype.updateCellInfoFromSystem = function () {
  55530. this.cellIndex = this.particleSystem.startSpriteCellID;
  55531. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55532. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55533. }
  55534. else {
  55535. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55536. }
  55537. };
  55538. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55539. // (ageOffset / scaledUpdateSpeed) / available cells
  55540. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55541. this._currentFrameCounter += scaledUpdateSpeed;
  55542. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55543. this._currentFrameCounter = 0;
  55544. this.cellIndex++;
  55545. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55546. this.cellIndex = this.particleSystem.endSpriteCellID;
  55547. }
  55548. }
  55549. };
  55550. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55551. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55552. this.cellIndex++;
  55553. this._currentFrameCounter = 0;
  55554. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55555. if (this.particleSystem.spriteCellLoop) {
  55556. this.cellIndex = this.particleSystem.startSpriteCellID;
  55557. }
  55558. else {
  55559. this.cellIndex = this.particleSystem.endSpriteCellID;
  55560. }
  55561. }
  55562. }
  55563. else {
  55564. this._currentFrameCounter++;
  55565. }
  55566. };
  55567. /**
  55568. * Copy the properties of particle to another one.
  55569. * @param other the particle to copy the information to.
  55570. */
  55571. Particle.prototype.copyTo = function (other) {
  55572. other.position.copyFrom(this.position);
  55573. other.direction.copyFrom(this.direction);
  55574. other.color.copyFrom(this.color);
  55575. other.colorStep.copyFrom(this.colorStep);
  55576. other.lifeTime = this.lifeTime;
  55577. other.age = this.age;
  55578. other.size = this.size;
  55579. other.angle = this.angle;
  55580. other.angularSpeed = this.angularSpeed;
  55581. other.particleSystem = this.particleSystem;
  55582. other.cellIndex = this.cellIndex;
  55583. };
  55584. return Particle;
  55585. }());
  55586. BABYLON.Particle = Particle;
  55587. })(BABYLON || (BABYLON = {}));
  55588. //# sourceMappingURL=babylon.particle.js.map
  55589. var BABYLON;
  55590. (function (BABYLON) {
  55591. /**
  55592. * This represents a particle system in Babylon.
  55593. * 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.
  55594. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55595. * @example https://doc.babylonjs.com/babylon101/particles
  55596. */
  55597. var ParticleSystem = /** @class */ (function () {
  55598. /**
  55599. * Instantiates a particle system.
  55600. * 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.
  55601. * @param name The name of the particle system
  55602. * @param capacity The max number of particles alive at the same time
  55603. * @param scene The scene the particle system belongs to
  55604. * @param customEffect a custom effect used to change the way particles are rendered by default
  55605. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55606. * @param epsilon Offset used to render the particles
  55607. */
  55608. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55609. if (customEffect === void 0) { customEffect = null; }
  55610. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55611. if (epsilon === void 0) { epsilon = 0.01; }
  55612. var _this = this;
  55613. /**
  55614. * List of animations used by the particle system.
  55615. */
  55616. this.animations = [];
  55617. /**
  55618. * The rendering group used by the Particle system to chose when to render.
  55619. */
  55620. this.renderingGroupId = 0;
  55621. /**
  55622. * The emitter represents the Mesh or position we are attaching the particle system to.
  55623. */
  55624. this.emitter = null;
  55625. /**
  55626. * The maximum number of particles to emit per frame
  55627. */
  55628. this.emitRate = 10;
  55629. /**
  55630. * If you want to launch only a few particles at once, that can be done, as well.
  55631. */
  55632. this.manualEmitCount = -1;
  55633. /**
  55634. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55635. */
  55636. this.updateSpeed = 0.01;
  55637. /**
  55638. * The amount of time the particle system is running (depends of the overall update speed).
  55639. */
  55640. this.targetStopDuration = 0;
  55641. /**
  55642. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55643. */
  55644. this.disposeOnStop = false;
  55645. /**
  55646. * Minimum power of emitting particles.
  55647. */
  55648. this.minEmitPower = 1;
  55649. /**
  55650. * Maximum power of emitting particles.
  55651. */
  55652. this.maxEmitPower = 1;
  55653. /**
  55654. * Minimum life time of emitting particles.
  55655. */
  55656. this.minLifeTime = 1;
  55657. /**
  55658. * Maximum life time of emitting particles.
  55659. */
  55660. this.maxLifeTime = 1;
  55661. /**
  55662. * Minimum Size of emitting particles.
  55663. */
  55664. this.minSize = 1;
  55665. /**
  55666. * Maximum Size of emitting particles.
  55667. */
  55668. this.maxSize = 1;
  55669. /**
  55670. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55671. */
  55672. this.minAngularSpeed = 0;
  55673. /**
  55674. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55675. */
  55676. this.maxAngularSpeed = 0;
  55677. /**
  55678. * The layer mask we are rendering the particles through.
  55679. */
  55680. this.layerMask = 0x0FFFFFFF;
  55681. /**
  55682. * This can help using your own shader to render the particle system.
  55683. * The according effect will be created
  55684. */
  55685. this.customShader = null;
  55686. /**
  55687. * By default particle system starts as soon as they are created. This prevents the
  55688. * automatic start to happen and let you decide when to start emitting particles.
  55689. */
  55690. this.preventAutoStart = false;
  55691. /**
  55692. * Callback triggered when the particle animation is ending.
  55693. */
  55694. this.onAnimationEnd = null;
  55695. /**
  55696. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55697. */
  55698. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55699. /**
  55700. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55701. * to override the particles.
  55702. */
  55703. this.forceDepthWrite = false;
  55704. /**
  55705. * You can use gravity if you want to give an orientation to your particles.
  55706. */
  55707. this.gravity = BABYLON.Vector3.Zero();
  55708. /**
  55709. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55710. */
  55711. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55712. /**
  55713. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55714. */
  55715. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55716. /**
  55717. * Color the particle will have at the end of its lifetime.
  55718. */
  55719. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55720. /**
  55721. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55722. */
  55723. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55724. /**
  55725. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55726. */
  55727. this.spriteCellLoop = true;
  55728. /**
  55729. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55730. */
  55731. this.spriteCellChangeSpeed = 0;
  55732. /**
  55733. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55734. */
  55735. this.startSpriteCellID = 0;
  55736. /**
  55737. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55738. */
  55739. this.endSpriteCellID = 0;
  55740. /**
  55741. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55742. */
  55743. this.spriteCellWidth = 0;
  55744. /**
  55745. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55746. */
  55747. this.spriteCellHeight = 0;
  55748. /**
  55749. * An event triggered when the system is disposed.
  55750. */
  55751. this.onDisposeObservable = new BABYLON.Observable();
  55752. this._particles = new Array();
  55753. this._stockParticles = new Array();
  55754. this._newPartsExcess = 0;
  55755. this._vertexBuffers = {};
  55756. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55757. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55758. this._scaledDirection = BABYLON.Vector3.Zero();
  55759. this._scaledGravity = BABYLON.Vector3.Zero();
  55760. this._currentRenderId = -1;
  55761. this._started = false;
  55762. this._stopped = false;
  55763. this._actualFrame = 0;
  55764. this._vertexBufferSize = 11;
  55765. // start of sub system methods
  55766. /**
  55767. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55768. * Its lifetime will start back at 0.
  55769. */
  55770. this.recycleParticle = function (particle) {
  55771. var lastParticle = _this._particles.pop();
  55772. if (lastParticle !== particle) {
  55773. lastParticle.copyTo(particle);
  55774. }
  55775. _this._stockParticles.push(lastParticle);
  55776. };
  55777. this._createParticle = function () {
  55778. var particle;
  55779. if (_this._stockParticles.length !== 0) {
  55780. particle = _this._stockParticles.pop();
  55781. particle.age = 0;
  55782. particle.cellIndex = _this.startSpriteCellID;
  55783. }
  55784. else {
  55785. particle = new BABYLON.Particle(_this);
  55786. }
  55787. return particle;
  55788. };
  55789. this._emitFromParticle = function (particle) {
  55790. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55791. return;
  55792. }
  55793. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55794. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55795. subSystem._rootParticleSystem = _this;
  55796. _this.activeSubSystems.push(subSystem);
  55797. subSystem.start();
  55798. };
  55799. this._appendParticleVertexes = null;
  55800. this.id = name;
  55801. this.name = name;
  55802. this._capacity = capacity;
  55803. this._epsilon = epsilon;
  55804. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55805. if (isAnimationSheetEnabled) {
  55806. this._vertexBufferSize = 12;
  55807. }
  55808. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55809. this._customEffect = customEffect;
  55810. scene.particleSystems.push(this);
  55811. this._createIndexBuffer();
  55812. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55813. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55814. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55815. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55816. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55817. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55818. if (this._isAnimationSheetEnabled) {
  55819. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55820. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55821. }
  55822. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55823. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55824. this._vertexBuffers["options"] = options;
  55825. // Default emitter type
  55826. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55827. this.updateFunction = function (particles) {
  55828. for (var index = 0; index < particles.length; index++) {
  55829. var particle = particles[index];
  55830. particle.age += _this._scaledUpdateSpeed;
  55831. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55832. _this._emitFromParticle(particle);
  55833. _this.recycleParticle(particle);
  55834. index--;
  55835. continue;
  55836. }
  55837. else {
  55838. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55839. particle.color.addInPlace(_this._scaledColorStep);
  55840. if (particle.color.a < 0)
  55841. particle.color.a = 0;
  55842. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55843. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55844. particle.position.addInPlace(_this._scaledDirection);
  55845. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55846. particle.direction.addInPlace(_this._scaledGravity);
  55847. if (_this._isAnimationSheetEnabled) {
  55848. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55849. }
  55850. }
  55851. }
  55852. };
  55853. }
  55854. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55855. /**
  55856. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55857. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55858. */
  55859. get: function () {
  55860. if (this.particleEmitterType.direction1) {
  55861. return this.particleEmitterType.direction1;
  55862. }
  55863. return BABYLON.Vector3.Zero();
  55864. },
  55865. set: function (value) {
  55866. if (this.particleEmitterType.direction1) {
  55867. this.particleEmitterType.direction1 = value;
  55868. }
  55869. },
  55870. enumerable: true,
  55871. configurable: true
  55872. });
  55873. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55874. /**
  55875. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55876. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55877. */
  55878. get: function () {
  55879. if (this.particleEmitterType.direction2) {
  55880. return this.particleEmitterType.direction2;
  55881. }
  55882. return BABYLON.Vector3.Zero();
  55883. },
  55884. set: function (value) {
  55885. if (this.particleEmitterType.direction2) {
  55886. this.particleEmitterType.direction2 = value;
  55887. }
  55888. },
  55889. enumerable: true,
  55890. configurable: true
  55891. });
  55892. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55893. /**
  55894. * 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.
  55895. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55896. */
  55897. get: function () {
  55898. if (this.particleEmitterType.minEmitBox) {
  55899. return this.particleEmitterType.minEmitBox;
  55900. }
  55901. return BABYLON.Vector3.Zero();
  55902. },
  55903. set: function (value) {
  55904. if (this.particleEmitterType.minEmitBox) {
  55905. this.particleEmitterType.minEmitBox = value;
  55906. }
  55907. },
  55908. enumerable: true,
  55909. configurable: true
  55910. });
  55911. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55912. /**
  55913. * 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.
  55914. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55915. */
  55916. get: function () {
  55917. if (this.particleEmitterType.maxEmitBox) {
  55918. return this.particleEmitterType.maxEmitBox;
  55919. }
  55920. return BABYLON.Vector3.Zero();
  55921. },
  55922. set: function (value) {
  55923. if (this.particleEmitterType.maxEmitBox) {
  55924. this.particleEmitterType.maxEmitBox = value;
  55925. }
  55926. },
  55927. enumerable: true,
  55928. configurable: true
  55929. });
  55930. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55931. /**
  55932. * Sets a callback that will be triggered when the system is disposed.
  55933. */
  55934. set: function (callback) {
  55935. if (this._onDisposeObserver) {
  55936. this.onDisposeObservable.remove(this._onDisposeObserver);
  55937. }
  55938. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55939. },
  55940. enumerable: true,
  55941. configurable: true
  55942. });
  55943. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55944. /**
  55945. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55946. */
  55947. get: function () {
  55948. return this._isAnimationSheetEnabled;
  55949. },
  55950. enumerable: true,
  55951. configurable: true
  55952. });
  55953. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55954. //end of Sub-emitter
  55955. /**
  55956. * Gets the current list of active particles
  55957. */
  55958. get: function () {
  55959. return this._particles;
  55960. },
  55961. enumerable: true,
  55962. configurable: true
  55963. });
  55964. /**
  55965. * Returns the string "ParticleSystem"
  55966. * @returns a string containing the class name
  55967. */
  55968. ParticleSystem.prototype.getClassName = function () {
  55969. return "ParticleSystem";
  55970. };
  55971. ParticleSystem.prototype._createIndexBuffer = function () {
  55972. var indices = [];
  55973. var index = 0;
  55974. for (var count = 0; count < this._capacity; count++) {
  55975. indices.push(index);
  55976. indices.push(index + 1);
  55977. indices.push(index + 2);
  55978. indices.push(index);
  55979. indices.push(index + 2);
  55980. indices.push(index + 3);
  55981. index += 4;
  55982. }
  55983. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55984. };
  55985. /**
  55986. * Gets the maximum number of particles active at the same time.
  55987. * @returns The max number of active particles.
  55988. */
  55989. ParticleSystem.prototype.getCapacity = function () {
  55990. return this._capacity;
  55991. };
  55992. /**
  55993. * Gets Wether there are still active particles in the system.
  55994. * @returns True if it is alive, otherwise false.
  55995. */
  55996. ParticleSystem.prototype.isAlive = function () {
  55997. return this._alive;
  55998. };
  55999. /**
  56000. * Gets Wether the system has been started.
  56001. * @returns True if it has been started, otherwise false.
  56002. */
  56003. ParticleSystem.prototype.isStarted = function () {
  56004. return this._started;
  56005. };
  56006. /**
  56007. * Starts the particle system and begins to emit.
  56008. */
  56009. ParticleSystem.prototype.start = function () {
  56010. this._started = true;
  56011. this._stopped = false;
  56012. this._actualFrame = 0;
  56013. if (this.subEmitters && this.subEmitters.length != 0) {
  56014. this.activeSubSystems = new Array();
  56015. }
  56016. };
  56017. /**
  56018. * Stops the particle system.
  56019. * @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.
  56020. */
  56021. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56022. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56023. this._stopped = true;
  56024. if (stopSubEmitters) {
  56025. this._stopSubEmitters();
  56026. }
  56027. };
  56028. // animation sheet
  56029. /**
  56030. * Remove all active particles
  56031. */
  56032. ParticleSystem.prototype.reset = function () {
  56033. this._stockParticles = [];
  56034. this._particles = [];
  56035. };
  56036. /**
  56037. * @hidden (for internal use only)
  56038. */
  56039. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56040. var offset = index * this._vertexBufferSize;
  56041. this._vertexData[offset] = particle.position.x;
  56042. this._vertexData[offset + 1] = particle.position.y;
  56043. this._vertexData[offset + 2] = particle.position.z;
  56044. this._vertexData[offset + 3] = particle.color.r;
  56045. this._vertexData[offset + 4] = particle.color.g;
  56046. this._vertexData[offset + 5] = particle.color.b;
  56047. this._vertexData[offset + 6] = particle.color.a;
  56048. this._vertexData[offset + 7] = particle.angle;
  56049. this._vertexData[offset + 8] = particle.size;
  56050. this._vertexData[offset + 9] = offsetX;
  56051. this._vertexData[offset + 10] = offsetY;
  56052. };
  56053. /**
  56054. * @hidden (for internal use only)
  56055. */
  56056. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56057. if (offsetX === 0)
  56058. offsetX = this._epsilon;
  56059. else if (offsetX === 1)
  56060. offsetX = 1 - this._epsilon;
  56061. if (offsetY === 0)
  56062. offsetY = this._epsilon;
  56063. else if (offsetY === 1)
  56064. offsetY = 1 - this._epsilon;
  56065. var offset = index * this._vertexBufferSize;
  56066. this._vertexData[offset] = particle.position.x;
  56067. this._vertexData[offset + 1] = particle.position.y;
  56068. this._vertexData[offset + 2] = particle.position.z;
  56069. this._vertexData[offset + 3] = particle.color.r;
  56070. this._vertexData[offset + 4] = particle.color.g;
  56071. this._vertexData[offset + 5] = particle.color.b;
  56072. this._vertexData[offset + 6] = particle.color.a;
  56073. this._vertexData[offset + 7] = particle.angle;
  56074. this._vertexData[offset + 8] = particle.size;
  56075. this._vertexData[offset + 9] = offsetX;
  56076. this._vertexData[offset + 10] = offsetY;
  56077. this._vertexData[offset + 11] = particle.cellIndex;
  56078. };
  56079. ParticleSystem.prototype._stopSubEmitters = function () {
  56080. if (!this.activeSubSystems) {
  56081. return;
  56082. }
  56083. this.activeSubSystems.forEach(function (subSystem) {
  56084. subSystem.stop(true);
  56085. });
  56086. this.activeSubSystems = new Array();
  56087. };
  56088. ParticleSystem.prototype._removeFromRoot = function () {
  56089. if (!this._rootParticleSystem) {
  56090. return;
  56091. }
  56092. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56093. if (index !== -1) {
  56094. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56095. }
  56096. };
  56097. // end of sub system methods
  56098. ParticleSystem.prototype._update = function (newParticles) {
  56099. // Update current
  56100. this._alive = this._particles.length > 0;
  56101. this.updateFunction(this._particles);
  56102. // Add new ones
  56103. var worldMatrix;
  56104. if (this.emitter.position) {
  56105. var emitterMesh = this.emitter;
  56106. worldMatrix = emitterMesh.getWorldMatrix();
  56107. }
  56108. else {
  56109. var emitterPosition = this.emitter;
  56110. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56111. }
  56112. var particle;
  56113. for (var index = 0; index < newParticles; index++) {
  56114. if (this._particles.length === this._capacity) {
  56115. break;
  56116. }
  56117. particle = this._createParticle();
  56118. this._particles.push(particle);
  56119. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56120. if (this.startPositionFunction) {
  56121. this.startPositionFunction(worldMatrix, particle.position, particle);
  56122. }
  56123. else {
  56124. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56125. }
  56126. if (this.startDirectionFunction) {
  56127. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56128. }
  56129. else {
  56130. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56131. }
  56132. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56133. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56134. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56135. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56136. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56137. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56138. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56139. }
  56140. };
  56141. ParticleSystem.prototype._getEffect = function () {
  56142. if (this._customEffect) {
  56143. return this._customEffect;
  56144. }
  56145. ;
  56146. var defines = [];
  56147. if (this._scene.clipPlane) {
  56148. defines.push("#define CLIPPLANE");
  56149. }
  56150. if (this._isAnimationSheetEnabled) {
  56151. defines.push("#define ANIMATESHEET");
  56152. }
  56153. // Effect
  56154. var join = defines.join("\n");
  56155. if (this._cachedDefines !== join) {
  56156. this._cachedDefines = join;
  56157. var attributesNamesOrOptions;
  56158. var effectCreationOption;
  56159. if (this._isAnimationSheetEnabled) {
  56160. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56161. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56162. }
  56163. else {
  56164. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56165. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56166. }
  56167. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56168. }
  56169. return this._effect;
  56170. };
  56171. /**
  56172. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56173. */
  56174. ParticleSystem.prototype.animate = function () {
  56175. if (!this._started)
  56176. return;
  56177. var effect = this._getEffect();
  56178. // Check
  56179. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56180. return;
  56181. if (this._currentRenderId === this._scene.getRenderId()) {
  56182. return;
  56183. }
  56184. this._currentRenderId = this._scene.getRenderId();
  56185. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56186. // determine the number of particles we need to create
  56187. var newParticles;
  56188. if (this.manualEmitCount > -1) {
  56189. newParticles = this.manualEmitCount;
  56190. this._newPartsExcess = 0;
  56191. this.manualEmitCount = 0;
  56192. }
  56193. else {
  56194. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56195. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56196. }
  56197. if (this._newPartsExcess > 1.0) {
  56198. newParticles += this._newPartsExcess >> 0;
  56199. this._newPartsExcess -= this._newPartsExcess >> 0;
  56200. }
  56201. this._alive = false;
  56202. if (!this._stopped) {
  56203. this._actualFrame += this._scaledUpdateSpeed;
  56204. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56205. this.stop();
  56206. }
  56207. else {
  56208. newParticles = 0;
  56209. }
  56210. this._update(newParticles);
  56211. // Stopped?
  56212. if (this._stopped) {
  56213. if (!this._alive) {
  56214. this._started = false;
  56215. if (this.onAnimationEnd) {
  56216. this.onAnimationEnd();
  56217. }
  56218. if (this.disposeOnStop) {
  56219. this._scene._toBeDisposed.push(this);
  56220. }
  56221. }
  56222. }
  56223. // Animation sheet
  56224. if (this._isAnimationSheetEnabled) {
  56225. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56226. }
  56227. else {
  56228. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56229. }
  56230. // Update VBO
  56231. var offset = 0;
  56232. for (var index = 0; index < this._particles.length; index++) {
  56233. var particle = this._particles[index];
  56234. this._appendParticleVertexes(offset, particle);
  56235. offset += 4;
  56236. }
  56237. if (this._vertexBuffer) {
  56238. this._vertexBuffer.update(this._vertexData);
  56239. }
  56240. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56241. this.stop();
  56242. }
  56243. };
  56244. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56245. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56246. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56247. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56248. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56249. };
  56250. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56251. this._appendParticleVertex(offset++, particle, 0, 0);
  56252. this._appendParticleVertex(offset++, particle, 1, 0);
  56253. this._appendParticleVertex(offset++, particle, 1, 1);
  56254. this._appendParticleVertex(offset++, particle, 0, 1);
  56255. };
  56256. /**
  56257. * Rebuilds the particle system.
  56258. */
  56259. ParticleSystem.prototype.rebuild = function () {
  56260. this._createIndexBuffer();
  56261. if (this._vertexBuffer) {
  56262. this._vertexBuffer._rebuild();
  56263. }
  56264. };
  56265. /**
  56266. * Is this system ready to be used/rendered
  56267. * @return true if the system is ready
  56268. */
  56269. ParticleSystem.prototype.isReady = function () {
  56270. var effect = this._getEffect();
  56271. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56272. return false;
  56273. }
  56274. return true;
  56275. };
  56276. /**
  56277. * Renders the particle system in its current state.
  56278. * @returns the current number of particles
  56279. */
  56280. ParticleSystem.prototype.render = function () {
  56281. var effect = this._getEffect();
  56282. // Check
  56283. if (!this.isReady() || !this._particles.length) {
  56284. return 0;
  56285. }
  56286. var engine = this._scene.getEngine();
  56287. // Render
  56288. engine.enableEffect(effect);
  56289. engine.setState(false);
  56290. var viewMatrix = this._scene.getViewMatrix();
  56291. effect.setTexture("diffuseSampler", this.particleTexture);
  56292. effect.setMatrix("view", viewMatrix);
  56293. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56294. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56295. var baseSize = this.particleTexture.getBaseSize();
  56296. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56297. }
  56298. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56299. if (this._scene.clipPlane) {
  56300. var clipPlane = this._scene.clipPlane;
  56301. var invView = viewMatrix.clone();
  56302. invView.invert();
  56303. effect.setMatrix("invView", invView);
  56304. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56305. }
  56306. // VBOs
  56307. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56308. // Draw order
  56309. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56310. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56311. }
  56312. else {
  56313. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56314. }
  56315. if (this.forceDepthWrite) {
  56316. engine.setDepthWrite(true);
  56317. }
  56318. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56319. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56320. return this._particles.length;
  56321. };
  56322. /**
  56323. * Disposes the particle system and free the associated resources
  56324. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56325. */
  56326. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56327. if (disposeTexture === void 0) { disposeTexture = true; }
  56328. if (this._vertexBuffer) {
  56329. this._vertexBuffer.dispose();
  56330. this._vertexBuffer = null;
  56331. }
  56332. if (this._indexBuffer) {
  56333. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56334. this._indexBuffer = null;
  56335. }
  56336. if (disposeTexture && this.particleTexture) {
  56337. this.particleTexture.dispose();
  56338. this.particleTexture = null;
  56339. }
  56340. this._removeFromRoot();
  56341. // Remove from scene
  56342. var index = this._scene.particleSystems.indexOf(this);
  56343. if (index > -1) {
  56344. this._scene.particleSystems.splice(index, 1);
  56345. }
  56346. // Callback
  56347. this.onDisposeObservable.notifyObservers(this);
  56348. this.onDisposeObservable.clear();
  56349. };
  56350. /**
  56351. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56352. * @param radius The radius of the sphere to emit from
  56353. * @returns the emitter
  56354. */
  56355. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56356. if (radius === void 0) { radius = 1; }
  56357. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56358. this.particleEmitterType = particleEmitter;
  56359. return particleEmitter;
  56360. };
  56361. /**
  56362. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56363. * @param radius The radius of the sphere to emit from
  56364. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56365. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56366. * @returns the emitter
  56367. */
  56368. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56369. if (radius === void 0) { radius = 1; }
  56370. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56371. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56372. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56373. this.particleEmitterType = particleEmitter;
  56374. return particleEmitter;
  56375. };
  56376. /**
  56377. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56378. * @param radius The radius of the cone to emit from
  56379. * @param angle The base angle of the cone
  56380. * @returns the emitter
  56381. */
  56382. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56383. if (radius === void 0) { radius = 1; }
  56384. if (angle === void 0) { angle = Math.PI / 4; }
  56385. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56386. this.particleEmitterType = particleEmitter;
  56387. return particleEmitter;
  56388. };
  56389. // 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.
  56390. /**
  56391. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56392. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56393. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56394. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56395. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56396. * @returns the emitter
  56397. */
  56398. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56399. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56400. this.particleEmitterType = particleEmitter;
  56401. this.direction1 = direction1;
  56402. this.direction2 = direction2;
  56403. this.minEmitBox = minEmitBox;
  56404. this.maxEmitBox = maxEmitBox;
  56405. return particleEmitter;
  56406. };
  56407. // Clone
  56408. /**
  56409. * Clones the particle system.
  56410. * @param name The name of the cloned object
  56411. * @param newEmitter The new emitter to use
  56412. * @returns the cloned particle system
  56413. */
  56414. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56415. var custom = null;
  56416. var program = null;
  56417. if (this.customShader != null) {
  56418. program = this.customShader;
  56419. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56420. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56421. }
  56422. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56423. result.customShader = program;
  56424. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56425. if (newEmitter === undefined) {
  56426. newEmitter = this.emitter;
  56427. }
  56428. result.emitter = newEmitter;
  56429. if (this.particleTexture) {
  56430. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56431. }
  56432. if (!this.preventAutoStart) {
  56433. result.start();
  56434. }
  56435. return result;
  56436. };
  56437. /**
  56438. * Serializes the particle system to a JSON object.
  56439. * @returns the JSON object
  56440. */
  56441. ParticleSystem.prototype.serialize = function () {
  56442. var serializationObject = {};
  56443. serializationObject.name = this.name;
  56444. serializationObject.id = this.id;
  56445. // Emitter
  56446. if (this.emitter.position) {
  56447. var emitterMesh = this.emitter;
  56448. serializationObject.emitterId = emitterMesh.id;
  56449. }
  56450. else {
  56451. var emitterPosition = this.emitter;
  56452. serializationObject.emitter = emitterPosition.asArray();
  56453. }
  56454. serializationObject.capacity = this.getCapacity();
  56455. if (this.particleTexture) {
  56456. serializationObject.textureName = this.particleTexture.name;
  56457. }
  56458. // Animations
  56459. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56460. // Particle system
  56461. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56462. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56463. serializationObject.minSize = this.minSize;
  56464. serializationObject.maxSize = this.maxSize;
  56465. serializationObject.minEmitPower = this.minEmitPower;
  56466. serializationObject.maxEmitPower = this.maxEmitPower;
  56467. serializationObject.minLifeTime = this.minLifeTime;
  56468. serializationObject.maxLifeTime = this.maxLifeTime;
  56469. serializationObject.emitRate = this.emitRate;
  56470. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56471. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56472. serializationObject.gravity = this.gravity.asArray();
  56473. serializationObject.direction1 = this.direction1.asArray();
  56474. serializationObject.direction2 = this.direction2.asArray();
  56475. serializationObject.color1 = this.color1.asArray();
  56476. serializationObject.color2 = this.color2.asArray();
  56477. serializationObject.colorDead = this.colorDead.asArray();
  56478. serializationObject.updateSpeed = this.updateSpeed;
  56479. serializationObject.targetStopDuration = this.targetStopDuration;
  56480. serializationObject.textureMask = this.textureMask.asArray();
  56481. serializationObject.blendMode = this.blendMode;
  56482. serializationObject.customShader = this.customShader;
  56483. serializationObject.preventAutoStart = this.preventAutoStart;
  56484. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56485. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56486. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56487. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56488. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56489. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56490. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56491. // Emitter
  56492. if (this.particleEmitterType) {
  56493. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56494. }
  56495. return serializationObject;
  56496. };
  56497. /**
  56498. * Parses a JSON object to create a particle system.
  56499. * @param parsedParticleSystem The JSON object to parse
  56500. * @param scene The scene to create the particle system in
  56501. * @param rootUrl The root url to use to load external dependencies like texture
  56502. * @returns the Parsed particle system
  56503. */
  56504. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56505. var name = parsedParticleSystem.name;
  56506. var custom = null;
  56507. var program = null;
  56508. if (parsedParticleSystem.customShader) {
  56509. program = parsedParticleSystem.customShader;
  56510. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56511. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56512. }
  56513. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56514. particleSystem.customShader = program;
  56515. if (parsedParticleSystem.id) {
  56516. particleSystem.id = parsedParticleSystem.id;
  56517. }
  56518. // Auto start
  56519. if (parsedParticleSystem.preventAutoStart) {
  56520. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56521. }
  56522. // Texture
  56523. if (parsedParticleSystem.textureName) {
  56524. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56525. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56526. }
  56527. // Emitter
  56528. if (parsedParticleSystem.emitterId) {
  56529. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56530. }
  56531. else {
  56532. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56533. }
  56534. // Animations
  56535. if (parsedParticleSystem.animations) {
  56536. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56537. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56538. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56539. }
  56540. }
  56541. if (parsedParticleSystem.autoAnimate) {
  56542. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56543. }
  56544. // Particle system
  56545. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56546. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56547. particleSystem.minSize = parsedParticleSystem.minSize;
  56548. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56549. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56550. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56551. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56552. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56553. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56554. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56555. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56556. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56557. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56558. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56559. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56560. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56561. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56562. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56563. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56564. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56565. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56566. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56567. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56568. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56569. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56570. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56571. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56572. if (!particleSystem.preventAutoStart) {
  56573. particleSystem.start();
  56574. }
  56575. return particleSystem;
  56576. };
  56577. /**
  56578. * Source color is added to the destination color without alpha affecting the result.
  56579. */
  56580. ParticleSystem.BLENDMODE_ONEONE = 0;
  56581. /**
  56582. * Blend current color and particle color using particle’s alpha.
  56583. */
  56584. ParticleSystem.BLENDMODE_STANDARD = 1;
  56585. return ParticleSystem;
  56586. }());
  56587. BABYLON.ParticleSystem = ParticleSystem;
  56588. })(BABYLON || (BABYLON = {}));
  56589. //# sourceMappingURL=babylon.particleSystem.js.map
  56590. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56591. var BABYLON;
  56592. (function (BABYLON) {
  56593. /**
  56594. * Particle emitter emitting particles from the inside of a box.
  56595. * It emits the particles randomly between 2 given directions.
  56596. */
  56597. var BoxParticleEmitter = /** @class */ (function () {
  56598. /**
  56599. * Creates a new instance BoxParticleEmitter
  56600. */
  56601. function BoxParticleEmitter() {
  56602. /**
  56603. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56604. */
  56605. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56606. /**
  56607. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56608. */
  56609. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56610. /**
  56611. * 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.
  56612. */
  56613. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56614. /**
  56615. * 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.
  56616. */
  56617. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56618. }
  56619. /**
  56620. * Called by the particle System when the direction is computed for the created particle.
  56621. * @param emitPower is the power of the particle (speed)
  56622. * @param worldMatrix is the world matrix of the particle system
  56623. * @param directionToUpdate is the direction vector to update with the result
  56624. * @param particle is the particle we are computed the direction for
  56625. */
  56626. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56627. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56628. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56629. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56630. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56631. };
  56632. /**
  56633. * Called by the particle System when the position is computed for the created particle.
  56634. * @param worldMatrix is the world matrix of the particle system
  56635. * @param positionToUpdate is the position vector to update with the result
  56636. * @param particle is the particle we are computed the position for
  56637. */
  56638. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56639. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56640. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56641. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56642. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56643. };
  56644. /**
  56645. * Clones the current emitter and returns a copy of it
  56646. * @returns the new emitter
  56647. */
  56648. BoxParticleEmitter.prototype.clone = function () {
  56649. var newOne = new BoxParticleEmitter();
  56650. BABYLON.Tools.DeepCopy(this, newOne);
  56651. return newOne;
  56652. };
  56653. /**
  56654. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56655. * @param effect defines the update shader
  56656. */
  56657. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56658. effect.setVector3("direction1", this.direction1);
  56659. effect.setVector3("direction2", this.direction2);
  56660. effect.setVector3("minEmitBox", this.minEmitBox);
  56661. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56662. };
  56663. /**
  56664. * Returns a string to use to update the GPU particles update shader
  56665. * @returns a string containng the defines string
  56666. */
  56667. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56668. return "#define BOXEMITTER";
  56669. };
  56670. /**
  56671. * Returns the string "BoxEmitter"
  56672. * @returns a string containing the class name
  56673. */
  56674. BoxParticleEmitter.prototype.getClassName = function () {
  56675. return "BoxEmitter";
  56676. };
  56677. /**
  56678. * Serializes the particle system to a JSON object.
  56679. * @returns the JSON object
  56680. */
  56681. BoxParticleEmitter.prototype.serialize = function () {
  56682. var serializationObject = {};
  56683. serializationObject.type = this.getClassName();
  56684. serializationObject.direction1 = this.direction1.asArray();
  56685. serializationObject.direction2 = this.direction2.asArray();
  56686. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56687. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56688. return serializationObject;
  56689. };
  56690. /**
  56691. * Parse properties from a JSON object
  56692. * @param serializationObject defines the JSON object
  56693. */
  56694. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56695. this.direction1.copyFrom(serializationObject.direction1);
  56696. this.direction2.copyFrom(serializationObject.direction2);
  56697. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56698. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56699. };
  56700. return BoxParticleEmitter;
  56701. }());
  56702. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56703. })(BABYLON || (BABYLON = {}));
  56704. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56705. var BABYLON;
  56706. (function (BABYLON) {
  56707. /**
  56708. * Particle emitter emitting particles from the inside of a cone.
  56709. * It emits the particles alongside the cone volume from the base to the particle.
  56710. * The emission direction might be randomized.
  56711. */
  56712. var ConeParticleEmitter = /** @class */ (function () {
  56713. /**
  56714. * Creates a new instance ConeParticleEmitter
  56715. * @param radius the radius of the emission cone (1 by default)
  56716. * @param angles the cone base angle (PI by default)
  56717. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56718. */
  56719. function ConeParticleEmitter(radius,
  56720. /**
  56721. * The radius of the emission cone.
  56722. */
  56723. angle,
  56724. /**
  56725. * The cone base angle.
  56726. */
  56727. directionRandomizer) {
  56728. if (radius === void 0) { radius = 1; }
  56729. if (angle === void 0) { angle = Math.PI; }
  56730. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56731. this.angle = angle;
  56732. this.directionRandomizer = directionRandomizer;
  56733. this.radius = radius;
  56734. }
  56735. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56736. /**
  56737. * Gets the radius of the emission cone.
  56738. */
  56739. get: function () {
  56740. return this._radius;
  56741. },
  56742. /**
  56743. * Sets the radius of the emission cone.
  56744. */
  56745. set: function (value) {
  56746. this._radius = value;
  56747. if (this.angle !== 0) {
  56748. this._height = value / Math.tan(this.angle / 2);
  56749. }
  56750. else {
  56751. this._height = 1;
  56752. }
  56753. },
  56754. enumerable: true,
  56755. configurable: true
  56756. });
  56757. /**
  56758. * Called by the particle System when the direction is computed for the created particle.
  56759. * @param emitPower is the power of the particle (speed)
  56760. * @param worldMatrix is the world matrix of the particle system
  56761. * @param directionToUpdate is the direction vector to update with the result
  56762. * @param particle is the particle we are computed the direction for
  56763. */
  56764. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56765. if (this.angle === 0) {
  56766. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56767. }
  56768. else {
  56769. // measure the direction Vector from the emitter to the particle.
  56770. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56771. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56772. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56773. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56774. direction.x += randX;
  56775. direction.y += randY;
  56776. direction.z += randZ;
  56777. direction.normalize();
  56778. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56779. }
  56780. };
  56781. /**
  56782. * Called by the particle System when the position is computed for the created particle.
  56783. * @param worldMatrix is the world matrix of the particle system
  56784. * @param positionToUpdate is the position vector to update with the result
  56785. * @param particle is the particle we are computed the position for
  56786. */
  56787. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56788. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56789. var h = BABYLON.Scalar.RandomRange(0, 1);
  56790. // Better distribution in a cone at normal angles.
  56791. h = 1 - h * h;
  56792. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56793. radius = radius * h;
  56794. var randX = radius * Math.sin(s);
  56795. var randZ = radius * Math.cos(s);
  56796. var randY = h * this._height;
  56797. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56798. };
  56799. /**
  56800. * Clones the current emitter and returns a copy of it
  56801. * @returns the new emitter
  56802. */
  56803. ConeParticleEmitter.prototype.clone = function () {
  56804. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56805. BABYLON.Tools.DeepCopy(this, newOne);
  56806. return newOne;
  56807. };
  56808. /**
  56809. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56810. * @param effect defines the update shader
  56811. */
  56812. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56813. effect.setFloat("radius", this.radius);
  56814. effect.setFloat("angle", this.angle);
  56815. effect.setFloat("height", this._height);
  56816. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56817. };
  56818. /**
  56819. * Returns a string to use to update the GPU particles update shader
  56820. * @returns a string containng the defines string
  56821. */
  56822. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56823. return "#define CONEEMITTER";
  56824. };
  56825. /**
  56826. * Returns the string "BoxEmitter"
  56827. * @returns a string containing the class name
  56828. */
  56829. ConeParticleEmitter.prototype.getClassName = function () {
  56830. return "ConeEmitter";
  56831. };
  56832. /**
  56833. * Serializes the particle system to a JSON object.
  56834. * @returns the JSON object
  56835. */
  56836. ConeParticleEmitter.prototype.serialize = function () {
  56837. var serializationObject = {};
  56838. serializationObject.type = this.getClassName();
  56839. serializationObject.radius = this.radius;
  56840. serializationObject.angle = this.angle;
  56841. serializationObject.directionRandomizer = this.directionRandomizer;
  56842. return serializationObject;
  56843. };
  56844. /**
  56845. * Parse properties from a JSON object
  56846. * @param serializationObject defines the JSON object
  56847. */
  56848. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56849. this.radius = serializationObject.radius;
  56850. this.angle = serializationObject.angle;
  56851. this.directionRandomizer = serializationObject.directionRandomizer;
  56852. };
  56853. return ConeParticleEmitter;
  56854. }());
  56855. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56856. })(BABYLON || (BABYLON = {}));
  56857. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56858. var BABYLON;
  56859. (function (BABYLON) {
  56860. /**
  56861. * Particle emitter emitting particles from the inside of a sphere.
  56862. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56863. */
  56864. var SphereParticleEmitter = /** @class */ (function () {
  56865. /**
  56866. * Creates a new instance SphereParticleEmitter
  56867. * @param radius the radius of the emission sphere (1 by default)
  56868. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56869. */
  56870. function SphereParticleEmitter(
  56871. /**
  56872. * The radius of the emission sphere.
  56873. */
  56874. radius,
  56875. /**
  56876. * How much to randomize the particle direction [0-1].
  56877. */
  56878. directionRandomizer) {
  56879. if (radius === void 0) { radius = 1; }
  56880. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56881. this.radius = radius;
  56882. this.directionRandomizer = directionRandomizer;
  56883. }
  56884. /**
  56885. * Called by the particle System when the direction is computed for the created particle.
  56886. * @param emitPower is the power of the particle (speed)
  56887. * @param worldMatrix is the world matrix of the particle system
  56888. * @param directionToUpdate is the direction vector to update with the result
  56889. * @param particle is the particle we are computed the direction for
  56890. */
  56891. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56892. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56893. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56894. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56895. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56896. direction.x += randX;
  56897. direction.y += randY;
  56898. direction.z += randZ;
  56899. direction.normalize();
  56900. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56901. };
  56902. /**
  56903. * Called by the particle System when the position is computed for the created particle.
  56904. * @param worldMatrix is the world matrix of the particle system
  56905. * @param positionToUpdate is the position vector to update with the result
  56906. * @param particle is the particle we are computed the position for
  56907. */
  56908. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56909. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56910. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56911. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56912. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56913. var randY = randRadius * Math.cos(theta);
  56914. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56915. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56916. };
  56917. /**
  56918. * Clones the current emitter and returns a copy of it
  56919. * @returns the new emitter
  56920. */
  56921. SphereParticleEmitter.prototype.clone = function () {
  56922. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56923. BABYLON.Tools.DeepCopy(this, newOne);
  56924. return newOne;
  56925. };
  56926. /**
  56927. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56928. * @param effect defines the update shader
  56929. */
  56930. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56931. effect.setFloat("radius", this.radius);
  56932. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56933. };
  56934. /**
  56935. * Returns a string to use to update the GPU particles update shader
  56936. * @returns a string containng the defines string
  56937. */
  56938. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56939. return "#define SPHEREEMITTER";
  56940. };
  56941. /**
  56942. * Returns the string "SphereParticleEmitter"
  56943. * @returns a string containing the class name
  56944. */
  56945. SphereParticleEmitter.prototype.getClassName = function () {
  56946. return "SphereParticleEmitter";
  56947. };
  56948. /**
  56949. * Serializes the particle system to a JSON object.
  56950. * @returns the JSON object
  56951. */
  56952. SphereParticleEmitter.prototype.serialize = function () {
  56953. var serializationObject = {};
  56954. serializationObject.type = this.getClassName();
  56955. serializationObject.radius = this.radius;
  56956. serializationObject.directionRandomizer = this.directionRandomizer;
  56957. return serializationObject;
  56958. };
  56959. /**
  56960. * Parse properties from a JSON object
  56961. * @param serializationObject defines the JSON object
  56962. */
  56963. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56964. this.radius = serializationObject.radius;
  56965. this.directionRandomizer = serializationObject.directionRandomizer;
  56966. };
  56967. return SphereParticleEmitter;
  56968. }());
  56969. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56970. /**
  56971. * Particle emitter emitting particles from the inside of a sphere.
  56972. * It emits the particles randomly between two vectors.
  56973. */
  56974. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56975. __extends(SphereDirectedParticleEmitter, _super);
  56976. /**
  56977. * Creates a new instance SphereDirectedParticleEmitter
  56978. * @param radius the radius of the emission sphere (1 by default)
  56979. * @param direction1 the min limit of the emission direction (up vector by default)
  56980. * @param direction2 the max limit of the emission direction (up vector by default)
  56981. */
  56982. function SphereDirectedParticleEmitter(radius,
  56983. /**
  56984. * The min limit of the emission direction.
  56985. */
  56986. direction1,
  56987. /**
  56988. * The max limit of the emission direction.
  56989. */
  56990. direction2) {
  56991. if (radius === void 0) { radius = 1; }
  56992. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56993. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56994. var _this = _super.call(this, radius) || this;
  56995. _this.direction1 = direction1;
  56996. _this.direction2 = direction2;
  56997. return _this;
  56998. }
  56999. /**
  57000. * Called by the particle System when the direction is computed for the created particle.
  57001. * @param emitPower is the power of the particle (speed)
  57002. * @param worldMatrix is the world matrix of the particle system
  57003. * @param directionToUpdate is the direction vector to update with the result
  57004. * @param particle is the particle we are computed the direction for
  57005. */
  57006. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57007. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57008. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57009. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57010. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57011. };
  57012. /**
  57013. * Clones the current emitter and returns a copy of it
  57014. * @returns the new emitter
  57015. */
  57016. SphereDirectedParticleEmitter.prototype.clone = function () {
  57017. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57018. BABYLON.Tools.DeepCopy(this, newOne);
  57019. return newOne;
  57020. };
  57021. /**
  57022. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57023. * @param effect defines the update shader
  57024. */
  57025. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57026. effect.setFloat("radius", this.radius);
  57027. effect.setVector3("direction1", this.direction1);
  57028. effect.setVector3("direction2", this.direction2);
  57029. };
  57030. /**
  57031. * Returns a string to use to update the GPU particles update shader
  57032. * @returns a string containng the defines string
  57033. */
  57034. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57035. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57036. };
  57037. /**
  57038. * Returns the string "SphereDirectedParticleEmitter"
  57039. * @returns a string containing the class name
  57040. */
  57041. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57042. return "SphereDirectedParticleEmitter";
  57043. };
  57044. /**
  57045. * Serializes the particle system to a JSON object.
  57046. * @returns the JSON object
  57047. */
  57048. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57049. var serializationObject = _super.prototype.serialize.call(this);
  57050. serializationObject.direction1 = this.direction1.asArray();
  57051. serializationObject.direction2 = this.direction2.asArray();
  57052. return serializationObject;
  57053. };
  57054. /**
  57055. * Parse properties from a JSON object
  57056. * @param serializationObject defines the JSON object
  57057. */
  57058. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57059. _super.prototype.parse.call(this, serializationObject);
  57060. this.direction1.copyFrom(serializationObject.direction1);
  57061. this.direction2.copyFrom(serializationObject.direction2);
  57062. };
  57063. return SphereDirectedParticleEmitter;
  57064. }(SphereParticleEmitter));
  57065. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57066. })(BABYLON || (BABYLON = {}));
  57067. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57068. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57069. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57070. s = arguments[i];
  57071. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57072. t[p] = s[p];
  57073. }
  57074. return t;
  57075. };
  57076. var BABYLON;
  57077. (function (BABYLON) {
  57078. /**
  57079. * This represents a GPU particle system in Babylon
  57080. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57081. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57082. */
  57083. var GPUParticleSystem = /** @class */ (function () {
  57084. /**
  57085. * Instantiates a GPU particle system.
  57086. * 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.
  57087. * @param name The name of the particle system
  57088. * @param capacity The max number of particles alive at the same time
  57089. * @param scene The scene the particle system belongs to
  57090. */
  57091. function GPUParticleSystem(name, options, scene) {
  57092. /**
  57093. * The emitter represents the Mesh or position we are attaching the particle system to.
  57094. */
  57095. this.emitter = null;
  57096. /**
  57097. * The rendering group used by the Particle system to chose when to render.
  57098. */
  57099. this.renderingGroupId = 0;
  57100. /**
  57101. * The layer mask we are rendering the particles through.
  57102. */
  57103. this.layerMask = 0x0FFFFFFF;
  57104. this._targetIndex = 0;
  57105. this._currentRenderId = -1;
  57106. this._started = false;
  57107. this._stopped = false;
  57108. this._timeDelta = 0;
  57109. this._attributesStrideSize = 14;
  57110. this._actualFrame = 0;
  57111. /**
  57112. * List of animations used by the particle system.
  57113. */
  57114. this.animations = [];
  57115. /**
  57116. * An event triggered when the system is disposed.
  57117. */
  57118. this.onDisposeObservable = new BABYLON.Observable();
  57119. /**
  57120. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57121. */
  57122. this.updateSpeed = 0.01;
  57123. /**
  57124. * The amount of time the particle system is running (depends of the overall update speed).
  57125. */
  57126. this.targetStopDuration = 0;
  57127. /**
  57128. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57129. */
  57130. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57131. /**
  57132. * Minimum life time of emitting particles.
  57133. */
  57134. this.minLifeTime = 1;
  57135. /**
  57136. * Maximum life time of emitting particles.
  57137. */
  57138. this.maxLifeTime = 1;
  57139. /**
  57140. * Minimum Size of emitting particles.
  57141. */
  57142. this.minSize = 1;
  57143. /**
  57144. * Maximum Size of emitting particles.
  57145. */
  57146. this.maxSize = 1;
  57147. /**
  57148. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57149. */
  57150. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57151. /**
  57152. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57153. */
  57154. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57155. /**
  57156. * Color the particle will have at the end of its lifetime.
  57157. */
  57158. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57159. /**
  57160. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57161. */
  57162. this.emitRate = 100;
  57163. /**
  57164. * You can use gravity if you want to give an orientation to your particles.
  57165. */
  57166. this.gravity = BABYLON.Vector3.Zero();
  57167. /**
  57168. * Minimum power of emitting particles.
  57169. */
  57170. this.minEmitPower = 1;
  57171. /**
  57172. * Maximum power of emitting particles.
  57173. */
  57174. this.maxEmitPower = 1;
  57175. /**
  57176. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57177. * to override the particles.
  57178. */
  57179. this.forceDepthWrite = false;
  57180. this.id = name;
  57181. this.name = name;
  57182. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57183. this._engine = this._scene.getEngine();
  57184. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57185. this._capacity = fullOptions.capacity;
  57186. this._activeCount = fullOptions.capacity;
  57187. this._currentActiveCount = 0;
  57188. this._scene.particleSystems.push(this);
  57189. this._updateEffectOptions = {
  57190. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57191. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57192. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57193. uniformBuffersNames: [],
  57194. samplers: ["randomSampler"],
  57195. defines: "",
  57196. fallbacks: null,
  57197. onCompiled: null,
  57198. onError: null,
  57199. indexParameters: null,
  57200. maxSimultaneousLights: 0,
  57201. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57202. };
  57203. // Random data
  57204. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57205. var d = [];
  57206. for (var i = 0; i < maxTextureSize; ++i) {
  57207. d.push(Math.random());
  57208. d.push(Math.random());
  57209. d.push(Math.random());
  57210. d.push(Math.random());
  57211. }
  57212. 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);
  57213. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57214. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57215. this._randomTextureSize = maxTextureSize;
  57216. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57217. }
  57218. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57219. /**
  57220. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57221. */
  57222. get: function () {
  57223. if (!BABYLON.Engine.LastCreatedEngine) {
  57224. return false;
  57225. }
  57226. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57227. },
  57228. enumerable: true,
  57229. configurable: true
  57230. });
  57231. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57232. /**
  57233. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57234. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57235. */
  57236. get: function () {
  57237. if (this.particleEmitterType.direction1) {
  57238. return this.particleEmitterType.direction1;
  57239. }
  57240. return BABYLON.Vector3.Zero();
  57241. },
  57242. set: function (value) {
  57243. if (this.particleEmitterType.direction1) {
  57244. this.particleEmitterType.direction1 = value;
  57245. }
  57246. },
  57247. enumerable: true,
  57248. configurable: true
  57249. });
  57250. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57251. /**
  57252. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57253. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57254. */
  57255. get: function () {
  57256. if (this.particleEmitterType.direction2) {
  57257. return this.particleEmitterType.direction2;
  57258. }
  57259. return BABYLON.Vector3.Zero();
  57260. },
  57261. set: function (value) {
  57262. if (this.particleEmitterType.direction2) {
  57263. this.particleEmitterType.direction2 = value;
  57264. }
  57265. },
  57266. enumerable: true,
  57267. configurable: true
  57268. });
  57269. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57270. /**
  57271. * 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.
  57272. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57273. */
  57274. get: function () {
  57275. if (this.particleEmitterType.minEmitBox) {
  57276. return this.particleEmitterType.minEmitBox;
  57277. }
  57278. return BABYLON.Vector3.Zero();
  57279. },
  57280. set: function (value) {
  57281. if (this.particleEmitterType.minEmitBox) {
  57282. this.particleEmitterType.minEmitBox = value;
  57283. }
  57284. },
  57285. enumerable: true,
  57286. configurable: true
  57287. });
  57288. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57289. /**
  57290. * 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.
  57291. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57292. */
  57293. get: function () {
  57294. if (this.particleEmitterType.maxEmitBox) {
  57295. return this.particleEmitterType.maxEmitBox;
  57296. }
  57297. return BABYLON.Vector3.Zero();
  57298. },
  57299. set: function (value) {
  57300. if (this.particleEmitterType.maxEmitBox) {
  57301. this.particleEmitterType.maxEmitBox = value;
  57302. }
  57303. },
  57304. enumerable: true,
  57305. configurable: true
  57306. });
  57307. /**
  57308. * Gets the maximum number of particles active at the same time.
  57309. * @returns The max number of active particles.
  57310. */
  57311. GPUParticleSystem.prototype.getCapacity = function () {
  57312. return this._capacity;
  57313. };
  57314. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57315. /**
  57316. * Gets or set the number of active particles
  57317. */
  57318. get: function () {
  57319. return this._activeCount;
  57320. },
  57321. set: function (value) {
  57322. this._activeCount = Math.min(value, this._capacity);
  57323. },
  57324. enumerable: true,
  57325. configurable: true
  57326. });
  57327. /**
  57328. * Is this system ready to be used/rendered
  57329. * @return true if the system is ready
  57330. */
  57331. GPUParticleSystem.prototype.isReady = function () {
  57332. if (!this._updateEffect) {
  57333. this._recreateUpdateEffect();
  57334. this._recreateRenderEffect();
  57335. return false;
  57336. }
  57337. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57338. return false;
  57339. }
  57340. return true;
  57341. };
  57342. /**
  57343. * Gets Wether the system has been started.
  57344. * @returns True if it has been started, otherwise false.
  57345. */
  57346. GPUParticleSystem.prototype.isStarted = function () {
  57347. return this._started;
  57348. };
  57349. /**
  57350. * Starts the particle system and begins to emit.
  57351. */
  57352. GPUParticleSystem.prototype.start = function () {
  57353. this._started = true;
  57354. this._stopped = false;
  57355. };
  57356. /**
  57357. * Stops the particle system.
  57358. */
  57359. GPUParticleSystem.prototype.stop = function () {
  57360. this._stopped = true;
  57361. };
  57362. /**
  57363. * Remove all active particles
  57364. */
  57365. GPUParticleSystem.prototype.reset = function () {
  57366. this._releaseBuffers();
  57367. this._releaseVAOs();
  57368. this._currentActiveCount = 0;
  57369. this._targetIndex = 0;
  57370. };
  57371. /**
  57372. * Returns the string "GPUParticleSystem"
  57373. * @returns a string containing the class name
  57374. */
  57375. GPUParticleSystem.prototype.getClassName = function () {
  57376. return "GPUParticleSystem";
  57377. };
  57378. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57379. var updateVertexBuffers = {};
  57380. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57381. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57382. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57383. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57384. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57385. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57386. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57387. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57388. this._engine.bindArrayBuffer(null);
  57389. return vao;
  57390. };
  57391. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57392. var renderVertexBuffers = {};
  57393. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57394. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57395. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57396. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57397. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57398. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57399. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57400. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57401. this._engine.bindArrayBuffer(null);
  57402. return vao;
  57403. };
  57404. GPUParticleSystem.prototype._initialize = function (force) {
  57405. if (force === void 0) { force = false; }
  57406. if (this._buffer0 && !force) {
  57407. return;
  57408. }
  57409. var engine = this._scene.getEngine();
  57410. var data = new Array();
  57411. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57412. // position
  57413. data.push(0.0);
  57414. data.push(0.0);
  57415. data.push(0.0);
  57416. // Age and life
  57417. data.push(0.0); // create the particle as a dead one to create a new one at start
  57418. data.push(0.0);
  57419. // Seed
  57420. data.push(Math.random());
  57421. // Size
  57422. data.push(0.0);
  57423. // color
  57424. data.push(0.0);
  57425. data.push(0.0);
  57426. data.push(0.0);
  57427. data.push(0.0);
  57428. // direction
  57429. data.push(0.0);
  57430. data.push(0.0);
  57431. data.push(0.0);
  57432. }
  57433. // Sprite data
  57434. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57435. -0.5, 0.5, 0, 1,
  57436. -0.5, -0.5, 0, 0,
  57437. 0.5, -0.5, 1, 0]);
  57438. // Buffers
  57439. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57440. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57441. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57442. // Update VAO
  57443. this._updateVAO = [];
  57444. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57445. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57446. // Render VAO
  57447. this._renderVAO = [];
  57448. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57449. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57450. // Links
  57451. this._sourceBuffer = this._buffer0;
  57452. this._targetBuffer = this._buffer1;
  57453. };
  57454. /** @hidden */
  57455. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57456. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57457. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57458. return;
  57459. }
  57460. this._updateEffectOptions.defines = defines;
  57461. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57462. };
  57463. /** @hidden */
  57464. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57465. var defines = "";
  57466. if (this._scene.clipPlane) {
  57467. defines = "\n#define CLIPPLANE";
  57468. }
  57469. if (this._renderEffect && this._renderEffect.defines === defines) {
  57470. return;
  57471. }
  57472. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57473. };
  57474. /**
  57475. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57476. */
  57477. GPUParticleSystem.prototype.animate = function () {
  57478. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57479. this._actualFrame += this._timeDelta;
  57480. if (!this._stopped) {
  57481. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57482. this.stop();
  57483. }
  57484. }
  57485. };
  57486. /**
  57487. * Renders the particle system in its current state.
  57488. * @returns the current number of particles
  57489. */
  57490. GPUParticleSystem.prototype.render = function () {
  57491. if (!this._started) {
  57492. return 0;
  57493. }
  57494. this._recreateUpdateEffect();
  57495. this._recreateRenderEffect();
  57496. if (!this.isReady()) {
  57497. return 0;
  57498. }
  57499. if (this._currentRenderId === this._scene.getRenderId()) {
  57500. return 0;
  57501. }
  57502. this._currentRenderId = this._scene.getRenderId();
  57503. // Get everything ready to render
  57504. this._initialize();
  57505. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57506. // Enable update effect
  57507. this._engine.enableEffect(this._updateEffect);
  57508. this._engine.setState(false);
  57509. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57510. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57511. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57512. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57513. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57514. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57515. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57516. this._updateEffect.setDirectColor4("color1", this.color1);
  57517. this._updateEffect.setDirectColor4("color2", this.color2);
  57518. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57519. this._updateEffect.setVector3("gravity", this.gravity);
  57520. if (this.particleEmitterType) {
  57521. this.particleEmitterType.applyToShader(this._updateEffect);
  57522. }
  57523. var emitterWM;
  57524. if (this.emitter.position) {
  57525. var emitterMesh = this.emitter;
  57526. emitterWM = emitterMesh.getWorldMatrix();
  57527. }
  57528. else {
  57529. var emitterPosition = this.emitter;
  57530. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57531. }
  57532. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57533. // Bind source VAO
  57534. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57535. // Update
  57536. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57537. this._engine.setRasterizerState(false);
  57538. this._engine.beginTransformFeedback();
  57539. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57540. this._engine.endTransformFeedback();
  57541. this._engine.setRasterizerState(true);
  57542. this._engine.bindTransformFeedbackBuffer(null);
  57543. // Enable render effect
  57544. this._engine.enableEffect(this._renderEffect);
  57545. var viewMatrix = this._scene.getViewMatrix();
  57546. this._renderEffect.setMatrix("view", viewMatrix);
  57547. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57548. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57549. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57550. if (this._scene.clipPlane) {
  57551. var clipPlane = this._scene.clipPlane;
  57552. var invView = viewMatrix.clone();
  57553. invView.invert();
  57554. this._renderEffect.setMatrix("invView", invView);
  57555. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57556. }
  57557. // Draw order
  57558. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57559. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57560. }
  57561. else {
  57562. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57563. }
  57564. if (this.forceDepthWrite) {
  57565. this._engine.setDepthWrite(true);
  57566. }
  57567. // Bind source VAO
  57568. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57569. // Render
  57570. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57571. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57572. // Switch VAOs
  57573. this._targetIndex++;
  57574. if (this._targetIndex === 2) {
  57575. this._targetIndex = 0;
  57576. }
  57577. // Switch buffers
  57578. var tmpBuffer = this._sourceBuffer;
  57579. this._sourceBuffer = this._targetBuffer;
  57580. this._targetBuffer = tmpBuffer;
  57581. return this._currentActiveCount;
  57582. };
  57583. /**
  57584. * Rebuilds the particle system
  57585. */
  57586. GPUParticleSystem.prototype.rebuild = function () {
  57587. this._initialize(true);
  57588. };
  57589. GPUParticleSystem.prototype._releaseBuffers = function () {
  57590. if (this._buffer0) {
  57591. this._buffer0.dispose();
  57592. this._buffer0 = null;
  57593. }
  57594. if (this._buffer1) {
  57595. this._buffer1.dispose();
  57596. this._buffer1 = null;
  57597. }
  57598. if (this._spriteBuffer) {
  57599. this._spriteBuffer.dispose();
  57600. this._spriteBuffer = null;
  57601. }
  57602. };
  57603. GPUParticleSystem.prototype._releaseVAOs = function () {
  57604. if (!this._updateVAO) {
  57605. return;
  57606. }
  57607. for (var index = 0; index < this._updateVAO.length; index++) {
  57608. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57609. }
  57610. this._updateVAO = [];
  57611. for (var index = 0; index < this._renderVAO.length; index++) {
  57612. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57613. }
  57614. this._renderVAO = [];
  57615. };
  57616. /**
  57617. * Disposes the particle system and free the associated resources
  57618. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57619. */
  57620. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57621. if (disposeTexture === void 0) { disposeTexture = true; }
  57622. var index = this._scene.particleSystems.indexOf(this);
  57623. if (index > -1) {
  57624. this._scene.particleSystems.splice(index, 1);
  57625. }
  57626. this._releaseBuffers();
  57627. this._releaseVAOs();
  57628. if (this._randomTexture) {
  57629. this._randomTexture.dispose();
  57630. this._randomTexture = null;
  57631. }
  57632. if (disposeTexture && this.particleTexture) {
  57633. this.particleTexture.dispose();
  57634. this.particleTexture = null;
  57635. }
  57636. // Callback
  57637. this.onDisposeObservable.notifyObservers(this);
  57638. this.onDisposeObservable.clear();
  57639. };
  57640. /**
  57641. * Clones the particle system.
  57642. * @param name The name of the cloned object
  57643. * @param newEmitter The new emitter to use
  57644. * @returns the cloned particle system
  57645. */
  57646. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57647. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57648. BABYLON.Tools.DeepCopy(this, result);
  57649. if (newEmitter === undefined) {
  57650. newEmitter = this.emitter;
  57651. }
  57652. result.emitter = newEmitter;
  57653. if (this.particleTexture) {
  57654. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57655. }
  57656. return result;
  57657. };
  57658. /**
  57659. * Serializes the particle system to a JSON object.
  57660. * @returns the JSON object
  57661. */
  57662. GPUParticleSystem.prototype.serialize = function () {
  57663. var serializationObject = {};
  57664. serializationObject.name = this.name;
  57665. serializationObject.id = this.id;
  57666. // Emitter
  57667. if (this.emitter.position) {
  57668. var emitterMesh = this.emitter;
  57669. serializationObject.emitterId = emitterMesh.id;
  57670. }
  57671. else {
  57672. var emitterPosition = this.emitter;
  57673. serializationObject.emitter = emitterPosition.asArray();
  57674. }
  57675. serializationObject.capacity = this.getCapacity();
  57676. if (this.particleTexture) {
  57677. serializationObject.textureName = this.particleTexture.name;
  57678. }
  57679. // Animations
  57680. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57681. // Particle system
  57682. serializationObject.activeParticleCount = this.activeParticleCount;
  57683. serializationObject.randomTextureSize = this._randomTextureSize;
  57684. serializationObject.minSize = this.minSize;
  57685. serializationObject.maxSize = this.maxSize;
  57686. serializationObject.minEmitPower = this.minEmitPower;
  57687. serializationObject.maxEmitPower = this.maxEmitPower;
  57688. serializationObject.minLifeTime = this.minLifeTime;
  57689. serializationObject.maxLifeTime = this.maxLifeTime;
  57690. serializationObject.emitRate = this.emitRate;
  57691. serializationObject.gravity = this.gravity.asArray();
  57692. serializationObject.color1 = this.color1.asArray();
  57693. serializationObject.color2 = this.color2.asArray();
  57694. serializationObject.colorDead = this.colorDead.asArray();
  57695. serializationObject.updateSpeed = this.updateSpeed;
  57696. serializationObject.targetStopDuration = this.targetStopDuration;
  57697. serializationObject.blendMode = this.blendMode;
  57698. // Emitter
  57699. if (this.particleEmitterType) {
  57700. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57701. }
  57702. return serializationObject;
  57703. };
  57704. /**
  57705. * Parses a JSON object to create a GPU particle system.
  57706. * @param parsedParticleSystem The JSON object to parse
  57707. * @param scene The scene to create the particle system in
  57708. * @param rootUrl The root url to use to load external dependencies like texture
  57709. * @returns the parsed GPU particle system
  57710. */
  57711. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57712. var name = parsedParticleSystem.name;
  57713. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57714. if (parsedParticleSystem.id) {
  57715. particleSystem.id = parsedParticleSystem.id;
  57716. }
  57717. // Texture
  57718. if (parsedParticleSystem.textureName) {
  57719. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57720. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57721. }
  57722. // Emitter
  57723. if (parsedParticleSystem.emitterId) {
  57724. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57725. }
  57726. else {
  57727. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57728. }
  57729. // Animations
  57730. if (parsedParticleSystem.animations) {
  57731. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57732. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57733. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57734. }
  57735. }
  57736. // Particle system
  57737. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57738. particleSystem.minSize = parsedParticleSystem.minSize;
  57739. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57740. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57741. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57742. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57743. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57744. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57745. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57746. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57747. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57748. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57749. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57750. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57751. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57752. // Emitter
  57753. if (parsedParticleSystem.particleEmitterType) {
  57754. var emitterType = void 0;
  57755. switch (parsedParticleSystem.particleEmitterType.type) {
  57756. case "SphereEmitter":
  57757. emitterType = new BABYLON.SphereParticleEmitter();
  57758. break;
  57759. case "SphereDirectedParticleEmitter":
  57760. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57761. break;
  57762. case "ConeEmitter":
  57763. emitterType = new BABYLON.ConeParticleEmitter();
  57764. break;
  57765. case "BoxEmitter":
  57766. default:
  57767. emitterType = new BABYLON.BoxParticleEmitter();
  57768. break;
  57769. }
  57770. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57771. particleSystem.particleEmitterType = emitterType;
  57772. }
  57773. return particleSystem;
  57774. };
  57775. return GPUParticleSystem;
  57776. }());
  57777. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57778. })(BABYLON || (BABYLON = {}));
  57779. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57780. var BABYLON;
  57781. (function (BABYLON) {
  57782. /**
  57783. * Represents one particle of a solid particle system.
  57784. */
  57785. var SolidParticle = /** @class */ (function () {
  57786. /**
  57787. * Creates a Solid Particle object.
  57788. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57789. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57790. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57791. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57792. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57793. * @param shapeId (integer) is the model shape identifier in the SPS.
  57794. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57795. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57796. */
  57797. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57798. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57799. /**
  57800. * particle global index
  57801. */
  57802. this.idx = 0;
  57803. /**
  57804. * The color of the particle
  57805. */
  57806. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57807. /**
  57808. * The world space position of the particle.
  57809. */
  57810. this.position = BABYLON.Vector3.Zero();
  57811. /**
  57812. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57813. */
  57814. this.rotation = BABYLON.Vector3.Zero();
  57815. /**
  57816. * The scaling of the particle.
  57817. */
  57818. this.scaling = BABYLON.Vector3.One();
  57819. /**
  57820. * The uvs of the particle.
  57821. */
  57822. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57823. /**
  57824. * The current speed of the particle.
  57825. */
  57826. this.velocity = BABYLON.Vector3.Zero();
  57827. /**
  57828. * The pivot point in the particle local space.
  57829. */
  57830. this.pivot = BABYLON.Vector3.Zero();
  57831. /**
  57832. * Must the particle be translated from its pivot point in its local space ?
  57833. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57834. * Default : false
  57835. */
  57836. this.translateFromPivot = false;
  57837. /**
  57838. * Is the particle active or not ?
  57839. */
  57840. this.alive = true;
  57841. /**
  57842. * Is the particle visible or not ?
  57843. */
  57844. this.isVisible = true;
  57845. /**
  57846. * Index of this particle in the global "positions" array (Internal use)
  57847. */
  57848. this._pos = 0;
  57849. /**
  57850. * Index of this particle in the global "indices" array (Internal use)
  57851. */
  57852. this._ind = 0;
  57853. /**
  57854. * ModelShape id of this particle
  57855. */
  57856. this.shapeId = 0;
  57857. /**
  57858. * Index of the particle in its shape id (Internal use)
  57859. */
  57860. this.idxInShape = 0;
  57861. /**
  57862. * Still set as invisible in order to skip useless computations (Internal use)
  57863. */
  57864. this._stillInvisible = false;
  57865. /**
  57866. * Last computed particle rotation matrix
  57867. */
  57868. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57869. /**
  57870. * Parent particle Id, if any.
  57871. * Default null.
  57872. */
  57873. this.parentId = null;
  57874. /**
  57875. * Internal global position in the SPS.
  57876. */
  57877. this._globalPosition = BABYLON.Vector3.Zero();
  57878. this.idx = particleIndex;
  57879. this._pos = positionIndex;
  57880. this._ind = indiceIndex;
  57881. this._model = model;
  57882. this.shapeId = shapeId;
  57883. this.idxInShape = idxInShape;
  57884. this._sps = sps;
  57885. if (modelBoundingInfo) {
  57886. this._modelBoundingInfo = modelBoundingInfo;
  57887. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57888. }
  57889. }
  57890. Object.defineProperty(SolidParticle.prototype, "scale", {
  57891. /**
  57892. * Legacy support, changed scale to scaling
  57893. */
  57894. get: function () {
  57895. return this.scaling;
  57896. },
  57897. /**
  57898. * Legacy support, changed scale to scaling
  57899. */
  57900. set: function (scale) {
  57901. this.scaling = scale;
  57902. },
  57903. enumerable: true,
  57904. configurable: true
  57905. });
  57906. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57907. /**
  57908. * Legacy support, changed quaternion to rotationQuaternion
  57909. */
  57910. get: function () {
  57911. return this.rotationQuaternion;
  57912. },
  57913. /**
  57914. * Legacy support, changed quaternion to rotationQuaternion
  57915. */
  57916. set: function (q) {
  57917. this.rotationQuaternion = q;
  57918. },
  57919. enumerable: true,
  57920. configurable: true
  57921. });
  57922. /**
  57923. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57924. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57925. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57926. * @returns true if it intersects
  57927. */
  57928. SolidParticle.prototype.intersectsMesh = function (target) {
  57929. if (!this._boundingInfo || !target._boundingInfo) {
  57930. return false;
  57931. }
  57932. if (this._sps._bSphereOnly) {
  57933. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57934. }
  57935. return this._boundingInfo.intersects(target._boundingInfo, false);
  57936. };
  57937. return SolidParticle;
  57938. }());
  57939. BABYLON.SolidParticle = SolidParticle;
  57940. /**
  57941. * Represents the shape of the model used by one particle of a solid particle system.
  57942. * SPS internal tool, don't use it manually.
  57943. */
  57944. var ModelShape = /** @class */ (function () {
  57945. /**
  57946. * 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.
  57947. * SPS internal tool, don't use it manually.
  57948. * @hidden
  57949. */
  57950. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57951. /**
  57952. * length of the shape in the model indices array (internal use)
  57953. */
  57954. this._indicesLength = 0;
  57955. this.shapeID = id;
  57956. this._shape = shape;
  57957. this._indicesLength = indicesLength;
  57958. this._shapeUV = shapeUV;
  57959. this._positionFunction = posFunction;
  57960. this._vertexFunction = vtxFunction;
  57961. }
  57962. return ModelShape;
  57963. }());
  57964. BABYLON.ModelShape = ModelShape;
  57965. /**
  57966. * Represents a Depth Sorted Particle in the solid particle system.
  57967. */
  57968. var DepthSortedParticle = /** @class */ (function () {
  57969. function DepthSortedParticle() {
  57970. /**
  57971. * Index of the particle in the "indices" array
  57972. */
  57973. this.ind = 0;
  57974. /**
  57975. * Length of the particle shape in the "indices" array
  57976. */
  57977. this.indicesLength = 0;
  57978. /**
  57979. * Squared distance from the particle to the camera
  57980. */
  57981. this.sqDistance = 0.0;
  57982. }
  57983. return DepthSortedParticle;
  57984. }());
  57985. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57986. })(BABYLON || (BABYLON = {}));
  57987. //# sourceMappingURL=babylon.solidParticle.js.map
  57988. var BABYLON;
  57989. (function (BABYLON) {
  57990. /**
  57991. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57992. *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.
  57993. * The SPS is also a particle system. It provides some methods to manage the particles.
  57994. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57995. *
  57996. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57997. */
  57998. var SolidParticleSystem = /** @class */ (function () {
  57999. /**
  58000. * Creates a SPS (Solid Particle System) object.
  58001. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58002. * @param scene (Scene) is the scene in which the SPS is added.
  58003. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58004. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58005. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58006. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58007. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58008. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58009. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58010. */
  58011. function SolidParticleSystem(name, scene, options) {
  58012. /**
  58013. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58014. * Example : var p = SPS.particles[i];
  58015. */
  58016. this.particles = new Array();
  58017. /**
  58018. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58019. */
  58020. this.nbParticles = 0;
  58021. /**
  58022. * If the particles must ever face the camera (default false). Useful for planar particles.
  58023. */
  58024. this.billboard = false;
  58025. /**
  58026. * Recompute normals when adding a shape
  58027. */
  58028. this.recomputeNormals = true;
  58029. /**
  58030. * This a counter ofr your own usage. It's not set by any SPS functions.
  58031. */
  58032. this.counter = 0;
  58033. /**
  58034. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58035. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58036. */
  58037. this.vars = {};
  58038. /**
  58039. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58040. */
  58041. this._bSphereOnly = false;
  58042. /**
  58043. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58044. */
  58045. this._bSphereRadiusFactor = 1.0;
  58046. this._positions = new Array();
  58047. this._indices = new Array();
  58048. this._normals = new Array();
  58049. this._colors = new Array();
  58050. this._uvs = new Array();
  58051. this._index = 0; // indices index
  58052. this._updatable = true;
  58053. this._pickable = false;
  58054. this._isVisibilityBoxLocked = false;
  58055. this._alwaysVisible = false;
  58056. this._depthSort = false;
  58057. this._shapeCounter = 0;
  58058. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58059. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58060. this._computeParticleColor = true;
  58061. this._computeParticleTexture = true;
  58062. this._computeParticleRotation = true;
  58063. this._computeParticleVertex = false;
  58064. this._computeBoundingBox = false;
  58065. this._depthSortParticles = true;
  58066. this._cam_axisZ = BABYLON.Vector3.Zero();
  58067. this._cam_axisY = BABYLON.Vector3.Zero();
  58068. this._cam_axisX = BABYLON.Vector3.Zero();
  58069. this._axisZ = BABYLON.Axis.Z;
  58070. this._camDir = BABYLON.Vector3.Zero();
  58071. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58072. this._rotMatrix = new BABYLON.Matrix();
  58073. this._invertMatrix = new BABYLON.Matrix();
  58074. this._rotated = BABYLON.Vector3.Zero();
  58075. this._quaternion = new BABYLON.Quaternion();
  58076. this._vertex = BABYLON.Vector3.Zero();
  58077. this._normal = BABYLON.Vector3.Zero();
  58078. this._yaw = 0.0;
  58079. this._pitch = 0.0;
  58080. this._roll = 0.0;
  58081. this._halfroll = 0.0;
  58082. this._halfpitch = 0.0;
  58083. this._halfyaw = 0.0;
  58084. this._sinRoll = 0.0;
  58085. this._cosRoll = 0.0;
  58086. this._sinPitch = 0.0;
  58087. this._cosPitch = 0.0;
  58088. this._sinYaw = 0.0;
  58089. this._cosYaw = 0.0;
  58090. this._mustUnrotateFixedNormals = false;
  58091. this._minimum = BABYLON.Vector3.Zero();
  58092. this._maximum = BABYLON.Vector3.Zero();
  58093. this._minBbox = BABYLON.Vector3.Zero();
  58094. this._maxBbox = BABYLON.Vector3.Zero();
  58095. this._particlesIntersect = false;
  58096. this._depthSortFunction = function (p1, p2) {
  58097. return (p2.sqDistance - p1.sqDistance);
  58098. };
  58099. this._needs32Bits = false;
  58100. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58101. this._scaledPivot = BABYLON.Vector3.Zero();
  58102. this._particleHasParent = false;
  58103. this.name = name;
  58104. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58105. this._camera = scene.activeCamera;
  58106. this._pickable = options ? options.isPickable : false;
  58107. this._depthSort = options ? options.enableDepthSort : false;
  58108. this._particlesIntersect = options ? options.particleIntersection : false;
  58109. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58110. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58111. if (options && options.updatable) {
  58112. this._updatable = options.updatable;
  58113. }
  58114. else {
  58115. this._updatable = true;
  58116. }
  58117. if (this._pickable) {
  58118. this.pickedParticles = [];
  58119. }
  58120. if (this._depthSort) {
  58121. this.depthSortedParticles = [];
  58122. }
  58123. }
  58124. /**
  58125. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58126. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58127. * @returns the created mesh
  58128. */
  58129. SolidParticleSystem.prototype.buildMesh = function () {
  58130. if (this.nbParticles === 0) {
  58131. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58132. this.addShape(triangle, 1);
  58133. triangle.dispose();
  58134. }
  58135. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58136. this._positions32 = new Float32Array(this._positions);
  58137. this._uvs32 = new Float32Array(this._uvs);
  58138. this._colors32 = new Float32Array(this._colors);
  58139. if (this.recomputeNormals) {
  58140. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58141. }
  58142. this._normals32 = new Float32Array(this._normals);
  58143. this._fixedNormal32 = new Float32Array(this._normals);
  58144. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58145. this._unrotateFixedNormals();
  58146. }
  58147. var vertexData = new BABYLON.VertexData();
  58148. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58149. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58150. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58151. if (this._uvs32.length > 0) {
  58152. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58153. }
  58154. if (this._colors32.length > 0) {
  58155. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58156. }
  58157. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58158. vertexData.applyToMesh(mesh, this._updatable);
  58159. this.mesh = mesh;
  58160. this.mesh.isPickable = this._pickable;
  58161. // free memory
  58162. if (!this._depthSort) {
  58163. this._indices = null;
  58164. }
  58165. this._positions = null;
  58166. this._normals = null;
  58167. this._uvs = null;
  58168. this._colors = null;
  58169. if (!this._updatable) {
  58170. this.particles.length = 0;
  58171. }
  58172. return mesh;
  58173. };
  58174. /**
  58175. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58176. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58177. * Thus the particles generated from `digest()` have their property `position` set yet.
  58178. * @param mesh ( Mesh ) is the mesh to be digested
  58179. * @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
  58180. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58181. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58182. * @returns the current SPS
  58183. */
  58184. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58185. var size = (options && options.facetNb) || 1;
  58186. var number = (options && options.number) || 0;
  58187. var delta = (options && options.delta) || 0;
  58188. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58189. var meshInd = mesh.getIndices();
  58190. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58191. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58192. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58193. var f = 0; // facet counter
  58194. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58195. // compute size from number
  58196. if (number) {
  58197. number = (number > totalFacets) ? totalFacets : number;
  58198. size = Math.round(totalFacets / number);
  58199. delta = 0;
  58200. }
  58201. else {
  58202. size = (size > totalFacets) ? totalFacets : size;
  58203. }
  58204. var facetPos = []; // submesh positions
  58205. var facetInd = []; // submesh indices
  58206. var facetUV = []; // submesh UV
  58207. var facetCol = []; // submesh colors
  58208. var barycenter = BABYLON.Vector3.Zero();
  58209. var sizeO = size;
  58210. while (f < totalFacets) {
  58211. size = sizeO + Math.floor((1 + delta) * Math.random());
  58212. if (f > totalFacets - size) {
  58213. size = totalFacets - f;
  58214. }
  58215. // reset temp arrays
  58216. facetPos.length = 0;
  58217. facetInd.length = 0;
  58218. facetUV.length = 0;
  58219. facetCol.length = 0;
  58220. // iterate over "size" facets
  58221. var fi = 0;
  58222. for (var j = f * 3; j < (f + size) * 3; j++) {
  58223. facetInd.push(fi);
  58224. var i = meshInd[j];
  58225. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58226. if (meshUV) {
  58227. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58228. }
  58229. if (meshCol) {
  58230. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58231. }
  58232. fi++;
  58233. }
  58234. // create a model shape for each single particle
  58235. var idx = this.nbParticles;
  58236. var shape = this._posToShape(facetPos);
  58237. var shapeUV = this._uvsToShapeUV(facetUV);
  58238. // compute the barycenter of the shape
  58239. var v;
  58240. for (v = 0; v < shape.length; v++) {
  58241. barycenter.addInPlace(shape[v]);
  58242. }
  58243. barycenter.scaleInPlace(1 / shape.length);
  58244. // shift the shape from its barycenter to the origin
  58245. for (v = 0; v < shape.length; v++) {
  58246. shape[v].subtractInPlace(barycenter);
  58247. }
  58248. var bInfo;
  58249. if (this._particlesIntersect) {
  58250. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58251. }
  58252. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58253. // add the particle in the SPS
  58254. var currentPos = this._positions.length;
  58255. var currentInd = this._indices.length;
  58256. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58257. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58258. // initialize the particle position
  58259. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58260. this._index += shape.length;
  58261. idx++;
  58262. this.nbParticles++;
  58263. this._shapeCounter++;
  58264. f += size;
  58265. }
  58266. return this;
  58267. };
  58268. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58269. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58270. var index = 0;
  58271. var idx = 0;
  58272. for (var p = 0; p < this.particles.length; p++) {
  58273. this._particle = this.particles[p];
  58274. this._shape = this._particle._model._shape;
  58275. if (this._particle.rotationQuaternion) {
  58276. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58277. }
  58278. else {
  58279. this._yaw = this._particle.rotation.y;
  58280. this._pitch = this._particle.rotation.x;
  58281. this._roll = this._particle.rotation.z;
  58282. this._quaternionRotationYPR();
  58283. }
  58284. this._quaternionToRotationMatrix();
  58285. this._rotMatrix.invertToRef(this._invertMatrix);
  58286. for (var pt = 0; pt < this._shape.length; pt++) {
  58287. idx = index + pt * 3;
  58288. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58289. this._fixedNormal32[idx] = this._normal.x;
  58290. this._fixedNormal32[idx + 1] = this._normal.y;
  58291. this._fixedNormal32[idx + 2] = this._normal.z;
  58292. }
  58293. index = idx + 3;
  58294. }
  58295. };
  58296. //reset copy
  58297. SolidParticleSystem.prototype._resetCopy = function () {
  58298. this._copy.position.x = 0;
  58299. this._copy.position.y = 0;
  58300. this._copy.position.z = 0;
  58301. this._copy.rotation.x = 0;
  58302. this._copy.rotation.y = 0;
  58303. this._copy.rotation.z = 0;
  58304. this._copy.rotationQuaternion = null;
  58305. this._copy.scaling.x = 1.0;
  58306. this._copy.scaling.y = 1.0;
  58307. this._copy.scaling.z = 1.0;
  58308. this._copy.uvs.x = 0;
  58309. this._copy.uvs.y = 0;
  58310. this._copy.uvs.z = 1.0;
  58311. this._copy.uvs.w = 1.0;
  58312. this._copy.color = null;
  58313. this._copy.translateFromPivot = false;
  58314. };
  58315. // _meshBuilder : inserts the shape model in the global SPS mesh
  58316. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58317. var i;
  58318. var u = 0;
  58319. var c = 0;
  58320. var n = 0;
  58321. this._resetCopy();
  58322. if (options && options.positionFunction) { // call to custom positionFunction
  58323. options.positionFunction(this._copy, idx, idxInShape);
  58324. this._mustUnrotateFixedNormals = true;
  58325. }
  58326. if (this._copy.rotationQuaternion) {
  58327. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58328. }
  58329. else {
  58330. this._yaw = this._copy.rotation.y;
  58331. this._pitch = this._copy.rotation.x;
  58332. this._roll = this._copy.rotation.z;
  58333. this._quaternionRotationYPR();
  58334. }
  58335. this._quaternionToRotationMatrix();
  58336. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58337. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58338. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58339. if (this._copy.translateFromPivot) {
  58340. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58341. }
  58342. else {
  58343. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58344. }
  58345. for (i = 0; i < shape.length; i++) {
  58346. this._vertex.x = shape[i].x;
  58347. this._vertex.y = shape[i].y;
  58348. this._vertex.z = shape[i].z;
  58349. if (options && options.vertexFunction) {
  58350. options.vertexFunction(this._copy, this._vertex, i);
  58351. }
  58352. this._vertex.x *= this._copy.scaling.x;
  58353. this._vertex.y *= this._copy.scaling.y;
  58354. this._vertex.z *= this._copy.scaling.z;
  58355. this._vertex.x -= this._scaledPivot.x;
  58356. this._vertex.y -= this._scaledPivot.y;
  58357. this._vertex.z -= this._scaledPivot.z;
  58358. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58359. this._rotated.addInPlace(this._pivotBackTranslation);
  58360. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58361. if (meshUV) {
  58362. 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);
  58363. u += 2;
  58364. }
  58365. if (this._copy.color) {
  58366. this._color = this._copy.color;
  58367. }
  58368. else if (meshCol && meshCol[c] !== undefined) {
  58369. this._color.r = meshCol[c];
  58370. this._color.g = meshCol[c + 1];
  58371. this._color.b = meshCol[c + 2];
  58372. this._color.a = meshCol[c + 3];
  58373. }
  58374. else {
  58375. this._color.r = 1.0;
  58376. this._color.g = 1.0;
  58377. this._color.b = 1.0;
  58378. this._color.a = 1.0;
  58379. }
  58380. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58381. c += 4;
  58382. if (!this.recomputeNormals && meshNor) {
  58383. this._normal.x = meshNor[n];
  58384. this._normal.y = meshNor[n + 1];
  58385. this._normal.z = meshNor[n + 2];
  58386. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58387. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58388. n += 3;
  58389. }
  58390. }
  58391. for (i = 0; i < meshInd.length; i++) {
  58392. var current_ind = p + meshInd[i];
  58393. indices.push(current_ind);
  58394. if (current_ind > 65535) {
  58395. this._needs32Bits = true;
  58396. }
  58397. }
  58398. if (this._pickable) {
  58399. var nbfaces = meshInd.length / 3;
  58400. for (i = 0; i < nbfaces; i++) {
  58401. this.pickedParticles.push({ idx: idx, faceId: i });
  58402. }
  58403. }
  58404. if (this._depthSort) {
  58405. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58406. }
  58407. return this._copy;
  58408. };
  58409. // returns a shape array from positions array
  58410. SolidParticleSystem.prototype._posToShape = function (positions) {
  58411. var shape = [];
  58412. for (var i = 0; i < positions.length; i += 3) {
  58413. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58414. }
  58415. return shape;
  58416. };
  58417. // returns a shapeUV array from a Vector4 uvs
  58418. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58419. var shapeUV = [];
  58420. if (uvs) {
  58421. for (var i = 0; i < uvs.length; i++)
  58422. shapeUV.push(uvs[i]);
  58423. }
  58424. return shapeUV;
  58425. };
  58426. // adds a new particle object in the particles array
  58427. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58428. if (bInfo === void 0) { bInfo = null; }
  58429. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58430. this.particles.push(sp);
  58431. return sp;
  58432. };
  58433. /**
  58434. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58435. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58436. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58437. * @param nb (positive integer) the number of particles to be created from this model
  58438. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58439. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58440. * @returns the number of shapes in the system
  58441. */
  58442. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58443. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58444. var meshInd = mesh.getIndices();
  58445. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58446. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58447. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58448. var bbInfo;
  58449. if (this._particlesIntersect) {
  58450. bbInfo = mesh.getBoundingInfo();
  58451. }
  58452. var shape = this._posToShape(meshPos);
  58453. var shapeUV = this._uvsToShapeUV(meshUV);
  58454. var posfunc = options ? options.positionFunction : null;
  58455. var vtxfunc = options ? options.vertexFunction : null;
  58456. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58457. // particles
  58458. var sp;
  58459. var currentCopy;
  58460. var idx = this.nbParticles;
  58461. for (var i = 0; i < nb; i++) {
  58462. var currentPos = this._positions.length;
  58463. var currentInd = this._indices.length;
  58464. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58465. if (this._updatable) {
  58466. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58467. sp.position.copyFrom(currentCopy.position);
  58468. sp.rotation.copyFrom(currentCopy.rotation);
  58469. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58470. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58471. }
  58472. if (currentCopy.color && sp.color) {
  58473. sp.color.copyFrom(currentCopy.color);
  58474. }
  58475. sp.scaling.copyFrom(currentCopy.scaling);
  58476. sp.uvs.copyFrom(currentCopy.uvs);
  58477. }
  58478. this._index += shape.length;
  58479. idx++;
  58480. }
  58481. this.nbParticles += nb;
  58482. this._shapeCounter++;
  58483. return this._shapeCounter - 1;
  58484. };
  58485. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58486. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58487. this._resetCopy();
  58488. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58489. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58490. }
  58491. if (this._copy.rotationQuaternion) {
  58492. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58493. }
  58494. else {
  58495. this._yaw = this._copy.rotation.y;
  58496. this._pitch = this._copy.rotation.x;
  58497. this._roll = this._copy.rotation.z;
  58498. this._quaternionRotationYPR();
  58499. }
  58500. this._quaternionToRotationMatrix();
  58501. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58502. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58503. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58504. if (this._copy.translateFromPivot) {
  58505. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58506. }
  58507. else {
  58508. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58509. }
  58510. this._shape = particle._model._shape;
  58511. for (var pt = 0; pt < this._shape.length; pt++) {
  58512. this._vertex.x = this._shape[pt].x;
  58513. this._vertex.y = this._shape[pt].y;
  58514. this._vertex.z = this._shape[pt].z;
  58515. if (particle._model._vertexFunction) {
  58516. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58517. }
  58518. this._vertex.x *= this._copy.scaling.x;
  58519. this._vertex.y *= this._copy.scaling.y;
  58520. this._vertex.z *= this._copy.scaling.z;
  58521. this._vertex.x -= this._scaledPivot.x;
  58522. this._vertex.y -= this._scaledPivot.y;
  58523. this._vertex.z -= this._scaledPivot.z;
  58524. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58525. this._rotated.addInPlace(this._pivotBackTranslation);
  58526. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58527. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58528. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58529. }
  58530. particle.position.x = 0.0;
  58531. particle.position.y = 0.0;
  58532. particle.position.z = 0.0;
  58533. particle.rotation.x = 0.0;
  58534. particle.rotation.y = 0.0;
  58535. particle.rotation.z = 0.0;
  58536. particle.rotationQuaternion = null;
  58537. particle.scaling.x = 1.0;
  58538. particle.scaling.y = 1.0;
  58539. particle.scaling.z = 1.0;
  58540. particle.uvs.x = 0.0;
  58541. particle.uvs.y = 0.0;
  58542. particle.uvs.z = 1.0;
  58543. particle.uvs.w = 1.0;
  58544. particle.pivot.x = 0.0;
  58545. particle.pivot.y = 0.0;
  58546. particle.pivot.z = 0.0;
  58547. particle.translateFromPivot = false;
  58548. particle.parentId = null;
  58549. };
  58550. /**
  58551. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58552. * @returns the SPS.
  58553. */
  58554. SolidParticleSystem.prototype.rebuildMesh = function () {
  58555. for (var p = 0; p < this.particles.length; p++) {
  58556. this._rebuildParticle(this.particles[p]);
  58557. }
  58558. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58559. return this;
  58560. };
  58561. /**
  58562. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58563. * This method calls `updateParticle()` for each particle of the SPS.
  58564. * For an animated SPS, it is usually called within the render loop.
  58565. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58566. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58567. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58568. * @returns the SPS.
  58569. */
  58570. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58571. if (start === void 0) { start = 0; }
  58572. if (end === void 0) { end = this.nbParticles - 1; }
  58573. if (update === void 0) { update = true; }
  58574. if (!this._updatable) {
  58575. return this;
  58576. }
  58577. // custom beforeUpdate
  58578. this.beforeUpdateParticles(start, end, update);
  58579. this._cam_axisX.x = 1.0;
  58580. this._cam_axisX.y = 0.0;
  58581. this._cam_axisX.z = 0.0;
  58582. this._cam_axisY.x = 0.0;
  58583. this._cam_axisY.y = 1.0;
  58584. this._cam_axisY.z = 0.0;
  58585. this._cam_axisZ.x = 0.0;
  58586. this._cam_axisZ.y = 0.0;
  58587. this._cam_axisZ.z = 1.0;
  58588. // cases when the World Matrix is to be computed first
  58589. if (this.billboard || this._depthSort) {
  58590. this.mesh.computeWorldMatrix(true);
  58591. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58592. }
  58593. // if the particles will always face the camera
  58594. if (this.billboard) {
  58595. // compute the camera position and un-rotate it by the current mesh rotation
  58596. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58597. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58598. this._cam_axisZ.normalize();
  58599. // same for camera up vector extracted from the cam view matrix
  58600. var view = this._camera.getViewMatrix(true);
  58601. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58602. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58603. this._cam_axisY.normalize();
  58604. this._cam_axisX.normalize();
  58605. }
  58606. // if depthSort, compute the camera global position in the mesh local system
  58607. if (this._depthSort) {
  58608. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58609. }
  58610. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58611. var idx = 0; // current position index in the global array positions32
  58612. var index = 0; // position start index in the global array positions32 of the current particle
  58613. var colidx = 0; // current color index in the global array colors32
  58614. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58615. var uvidx = 0; // current uv index in the global array uvs32
  58616. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58617. var pt = 0; // current index in the particle model shape
  58618. if (this.mesh.isFacetDataEnabled) {
  58619. this._computeBoundingBox = true;
  58620. }
  58621. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58622. if (this._computeBoundingBox) {
  58623. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58624. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58625. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58626. }
  58627. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58628. if (this.mesh._boundingInfo) {
  58629. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58630. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58631. }
  58632. }
  58633. }
  58634. // particle loop
  58635. index = this.particles[start]._pos;
  58636. var vpos = (index / 3) | 0;
  58637. colorIndex = vpos * 4;
  58638. uvIndex = vpos * 2;
  58639. for (var p = start; p <= end; p++) {
  58640. this._particle = this.particles[p];
  58641. this._shape = this._particle._model._shape;
  58642. this._shapeUV = this._particle._model._shapeUV;
  58643. // call to custom user function to update the particle properties
  58644. this.updateParticle(this._particle);
  58645. // camera-particle distance for depth sorting
  58646. if (this._depthSort && this._depthSortParticles) {
  58647. var dsp = this.depthSortedParticles[p];
  58648. dsp.ind = this._particle._ind;
  58649. dsp.indicesLength = this._particle._model._indicesLength;
  58650. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58651. }
  58652. // skip the computations for inactive or already invisible particles
  58653. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58654. // increment indexes for the next particle
  58655. pt = this._shape.length;
  58656. index += pt * 3;
  58657. colorIndex += pt * 4;
  58658. uvIndex += pt * 2;
  58659. continue;
  58660. }
  58661. if (this._particle.isVisible) {
  58662. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58663. this._particleHasParent = (this._particle.parentId !== null);
  58664. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58665. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58666. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58667. // particle rotation matrix
  58668. if (this.billboard) {
  58669. this._particle.rotation.x = 0.0;
  58670. this._particle.rotation.y = 0.0;
  58671. }
  58672. if (this._computeParticleRotation || this.billboard) {
  58673. if (this._particle.rotationQuaternion) {
  58674. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58675. }
  58676. else {
  58677. this._yaw = this._particle.rotation.y;
  58678. this._pitch = this._particle.rotation.x;
  58679. this._roll = this._particle.rotation.z;
  58680. this._quaternionRotationYPR();
  58681. }
  58682. this._quaternionToRotationMatrix();
  58683. }
  58684. if (this._particleHasParent) {
  58685. this._parent = this.particles[this._particle.parentId];
  58686. 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];
  58687. 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];
  58688. 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];
  58689. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58690. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58691. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58692. if (this._computeParticleRotation || this.billboard) {
  58693. 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];
  58694. 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];
  58695. 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];
  58696. 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];
  58697. 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];
  58698. 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];
  58699. 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];
  58700. 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];
  58701. 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];
  58702. }
  58703. }
  58704. else {
  58705. this._particle._globalPosition.x = this._particle.position.x;
  58706. this._particle._globalPosition.y = this._particle.position.y;
  58707. this._particle._globalPosition.z = this._particle.position.z;
  58708. if (this._computeParticleRotation || this.billboard) {
  58709. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58710. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58711. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58712. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58713. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58714. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58715. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58716. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58717. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58718. }
  58719. }
  58720. if (this._particle.translateFromPivot) {
  58721. this._pivotBackTranslation.x = 0.0;
  58722. this._pivotBackTranslation.y = 0.0;
  58723. this._pivotBackTranslation.z = 0.0;
  58724. }
  58725. else {
  58726. this._pivotBackTranslation.x = this._scaledPivot.x;
  58727. this._pivotBackTranslation.y = this._scaledPivot.y;
  58728. this._pivotBackTranslation.z = this._scaledPivot.z;
  58729. }
  58730. // particle vertex loop
  58731. for (pt = 0; pt < this._shape.length; pt++) {
  58732. idx = index + pt * 3;
  58733. colidx = colorIndex + pt * 4;
  58734. uvidx = uvIndex + pt * 2;
  58735. this._vertex.x = this._shape[pt].x;
  58736. this._vertex.y = this._shape[pt].y;
  58737. this._vertex.z = this._shape[pt].z;
  58738. if (this._computeParticleVertex) {
  58739. this.updateParticleVertex(this._particle, this._vertex, pt);
  58740. }
  58741. // positions
  58742. this._vertex.x *= this._particle.scaling.x;
  58743. this._vertex.y *= this._particle.scaling.y;
  58744. this._vertex.z *= this._particle.scaling.z;
  58745. this._vertex.x -= this._scaledPivot.x;
  58746. this._vertex.y -= this._scaledPivot.y;
  58747. this._vertex.z -= this._scaledPivot.z;
  58748. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58749. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58750. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58751. this._rotated.x += this._pivotBackTranslation.x;
  58752. this._rotated.y += this._pivotBackTranslation.y;
  58753. this._rotated.z += this._pivotBackTranslation.z;
  58754. 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;
  58755. 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;
  58756. 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;
  58757. if (this._computeBoundingBox) {
  58758. if (this._positions32[idx] < this._minimum.x) {
  58759. this._minimum.x = this._positions32[idx];
  58760. }
  58761. if (this._positions32[idx] > this._maximum.x) {
  58762. this._maximum.x = this._positions32[idx];
  58763. }
  58764. if (this._positions32[idx + 1] < this._minimum.y) {
  58765. this._minimum.y = this._positions32[idx + 1];
  58766. }
  58767. if (this._positions32[idx + 1] > this._maximum.y) {
  58768. this._maximum.y = this._positions32[idx + 1];
  58769. }
  58770. if (this._positions32[idx + 2] < this._minimum.z) {
  58771. this._minimum.z = this._positions32[idx + 2];
  58772. }
  58773. if (this._positions32[idx + 2] > this._maximum.z) {
  58774. this._maximum.z = this._positions32[idx + 2];
  58775. }
  58776. }
  58777. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58778. if (!this._computeParticleVertex) {
  58779. this._normal.x = this._fixedNormal32[idx];
  58780. this._normal.y = this._fixedNormal32[idx + 1];
  58781. this._normal.z = this._fixedNormal32[idx + 2];
  58782. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58783. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58784. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58785. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58786. 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;
  58787. 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;
  58788. }
  58789. if (this._computeParticleColor && this._particle.color) {
  58790. this._colors32[colidx] = this._particle.color.r;
  58791. this._colors32[colidx + 1] = this._particle.color.g;
  58792. this._colors32[colidx + 2] = this._particle.color.b;
  58793. this._colors32[colidx + 3] = this._particle.color.a;
  58794. }
  58795. if (this._computeParticleTexture) {
  58796. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58797. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58798. }
  58799. }
  58800. }
  58801. // particle just set invisible : scaled to zero and positioned at the origin
  58802. else {
  58803. this._particle._stillInvisible = true; // mark the particle as invisible
  58804. for (pt = 0; pt < this._shape.length; pt++) {
  58805. idx = index + pt * 3;
  58806. colidx = colorIndex + pt * 4;
  58807. uvidx = uvIndex + pt * 2;
  58808. this._positions32[idx] = 0.0;
  58809. this._positions32[idx + 1] = 0.0;
  58810. this._positions32[idx + 2] = 0.0;
  58811. this._normals32[idx] = 0.0;
  58812. this._normals32[idx + 1] = 0.0;
  58813. this._normals32[idx + 2] = 0.0;
  58814. if (this._computeParticleColor && this._particle.color) {
  58815. this._colors32[colidx] = this._particle.color.r;
  58816. this._colors32[colidx + 1] = this._particle.color.g;
  58817. this._colors32[colidx + 2] = this._particle.color.b;
  58818. this._colors32[colidx + 3] = this._particle.color.a;
  58819. }
  58820. if (this._computeParticleTexture) {
  58821. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58822. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58823. }
  58824. }
  58825. }
  58826. // if the particle intersections must be computed : update the bbInfo
  58827. if (this._particlesIntersect) {
  58828. var bInfo = this._particle._boundingInfo;
  58829. var bBox = bInfo.boundingBox;
  58830. var bSphere = bInfo.boundingSphere;
  58831. if (!this._bSphereOnly) {
  58832. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58833. for (var b = 0; b < bBox.vectors.length; b++) {
  58834. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58835. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58836. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58837. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58838. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58839. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58840. 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;
  58841. 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;
  58842. 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;
  58843. }
  58844. bBox._update(this.mesh._worldMatrix);
  58845. }
  58846. // place and scale the particle bouding sphere in the SPS local system, then update it
  58847. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58848. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58849. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58850. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58851. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58852. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58853. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58854. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58855. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58856. 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));
  58857. bSphere._update(this.mesh._worldMatrix);
  58858. }
  58859. // increment indexes for the next particle
  58860. index = idx + 3;
  58861. colorIndex = colidx + 4;
  58862. uvIndex = uvidx + 2;
  58863. }
  58864. // if the VBO must be updated
  58865. if (update) {
  58866. if (this._computeParticleColor) {
  58867. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58868. }
  58869. if (this._computeParticleTexture) {
  58870. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58871. }
  58872. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58873. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58874. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58875. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58876. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58877. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58878. for (var i = 0; i < this._normals32.length; i++) {
  58879. this._fixedNormal32[i] = this._normals32[i];
  58880. }
  58881. }
  58882. if (!this.mesh.areNormalsFrozen) {
  58883. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58884. }
  58885. }
  58886. if (this._depthSort && this._depthSortParticles) {
  58887. this.depthSortedParticles.sort(this._depthSortFunction);
  58888. var dspl = this.depthSortedParticles.length;
  58889. var sorted = 0;
  58890. var lind = 0;
  58891. var sind = 0;
  58892. var sid = 0;
  58893. for (sorted = 0; sorted < dspl; sorted++) {
  58894. lind = this.depthSortedParticles[sorted].indicesLength;
  58895. sind = this.depthSortedParticles[sorted].ind;
  58896. for (var i = 0; i < lind; i++) {
  58897. this._indices32[sid] = this._indices[sind + i];
  58898. sid++;
  58899. }
  58900. }
  58901. this.mesh.updateIndices(this._indices32);
  58902. }
  58903. }
  58904. if (this._computeBoundingBox) {
  58905. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58906. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58907. }
  58908. this.afterUpdateParticles(start, end, update);
  58909. return this;
  58910. };
  58911. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58912. this._halfroll = this._roll * 0.5;
  58913. this._halfpitch = this._pitch * 0.5;
  58914. this._halfyaw = this._yaw * 0.5;
  58915. this._sinRoll = Math.sin(this._halfroll);
  58916. this._cosRoll = Math.cos(this._halfroll);
  58917. this._sinPitch = Math.sin(this._halfpitch);
  58918. this._cosPitch = Math.cos(this._halfpitch);
  58919. this._sinYaw = Math.sin(this._halfyaw);
  58920. this._cosYaw = Math.cos(this._halfyaw);
  58921. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58922. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58923. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58924. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58925. };
  58926. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58927. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58928. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58929. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58930. this._rotMatrix.m[3] = 0;
  58931. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58932. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58933. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58934. this._rotMatrix.m[7] = 0;
  58935. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58936. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58937. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58938. this._rotMatrix.m[11] = 0;
  58939. this._rotMatrix.m[12] = 0;
  58940. this._rotMatrix.m[13] = 0;
  58941. this._rotMatrix.m[14] = 0;
  58942. this._rotMatrix.m[15] = 1.0;
  58943. };
  58944. /**
  58945. * Disposes the SPS.
  58946. */
  58947. SolidParticleSystem.prototype.dispose = function () {
  58948. this.mesh.dispose();
  58949. this.vars = null;
  58950. // drop references to internal big arrays for the GC
  58951. this._positions = null;
  58952. this._indices = null;
  58953. this._normals = null;
  58954. this._uvs = null;
  58955. this._colors = null;
  58956. this._indices32 = null;
  58957. this._positions32 = null;
  58958. this._normals32 = null;
  58959. this._fixedNormal32 = null;
  58960. this._uvs32 = null;
  58961. this._colors32 = null;
  58962. this.pickedParticles = null;
  58963. };
  58964. /**
  58965. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58966. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58967. * @returns the SPS.
  58968. */
  58969. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58970. if (!this._isVisibilityBoxLocked) {
  58971. this.mesh.refreshBoundingInfo();
  58972. }
  58973. return this;
  58974. };
  58975. /**
  58976. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58977. * @param size the size (float) of the visibility box
  58978. * note : this doesn't lock the SPS mesh bounding box.
  58979. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58980. */
  58981. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58982. var vis = size / 2;
  58983. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58984. };
  58985. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58986. /**
  58987. * Gets whether the SPS as always visible or not
  58988. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58989. */
  58990. get: function () {
  58991. return this._alwaysVisible;
  58992. },
  58993. /**
  58994. * Sets the SPS as always visible or not
  58995. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58996. */
  58997. set: function (val) {
  58998. this._alwaysVisible = val;
  58999. this.mesh.alwaysSelectAsActiveMesh = val;
  59000. },
  59001. enumerable: true,
  59002. configurable: true
  59003. });
  59004. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59005. /**
  59006. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59007. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59008. */
  59009. get: function () {
  59010. return this._isVisibilityBoxLocked;
  59011. },
  59012. /**
  59013. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59014. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59015. */
  59016. set: function (val) {
  59017. this._isVisibilityBoxLocked = val;
  59018. var boundingInfo = this.mesh.getBoundingInfo();
  59019. boundingInfo.isLocked = val;
  59020. },
  59021. enumerable: true,
  59022. configurable: true
  59023. });
  59024. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59025. /**
  59026. * Gets if `setParticles()` computes the particle rotations or not.
  59027. * Default value : true. The SPS is faster when it's set to false.
  59028. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59029. */
  59030. get: function () {
  59031. return this._computeParticleRotation;
  59032. },
  59033. /**
  59034. * Tells to `setParticles()` to compute the particle rotations or not.
  59035. * Default value : true. The SPS is faster when it's set to false.
  59036. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59037. */
  59038. set: function (val) {
  59039. this._computeParticleRotation = val;
  59040. },
  59041. enumerable: true,
  59042. configurable: true
  59043. });
  59044. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59045. /**
  59046. * Gets if `setParticles()` computes the particle colors or not.
  59047. * Default value : true. The SPS is faster when it's set to false.
  59048. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59049. */
  59050. get: function () {
  59051. return this._computeParticleColor;
  59052. },
  59053. /**
  59054. * Tells to `setParticles()` to compute the particle colors or not.
  59055. * Default value : true. The SPS is faster when it's set to false.
  59056. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59057. */
  59058. set: function (val) {
  59059. this._computeParticleColor = val;
  59060. },
  59061. enumerable: true,
  59062. configurable: true
  59063. });
  59064. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59065. /**
  59066. * Gets if `setParticles()` computes the particle textures or not.
  59067. * Default value : true. The SPS is faster when it's set to false.
  59068. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59069. */
  59070. get: function () {
  59071. return this._computeParticleTexture;
  59072. },
  59073. set: function (val) {
  59074. this._computeParticleTexture = val;
  59075. },
  59076. enumerable: true,
  59077. configurable: true
  59078. });
  59079. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59080. /**
  59081. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59082. * Default value : false. The SPS is faster when it's set to false.
  59083. * Note : the particle custom vertex positions aren't stored values.
  59084. */
  59085. get: function () {
  59086. return this._computeParticleVertex;
  59087. },
  59088. /**
  59089. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59090. * Default value : false. The SPS is faster when it's set to false.
  59091. * Note : the particle custom vertex positions aren't stored values.
  59092. */
  59093. set: function (val) {
  59094. this._computeParticleVertex = val;
  59095. },
  59096. enumerable: true,
  59097. configurable: true
  59098. });
  59099. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59100. /**
  59101. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59102. */
  59103. get: function () {
  59104. return this._computeBoundingBox;
  59105. },
  59106. /**
  59107. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59108. */
  59109. set: function (val) {
  59110. this._computeBoundingBox = val;
  59111. },
  59112. enumerable: true,
  59113. configurable: true
  59114. });
  59115. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59116. /**
  59117. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59118. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59119. * Default : `true`
  59120. */
  59121. get: function () {
  59122. return this._depthSortParticles;
  59123. },
  59124. /**
  59125. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59126. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59127. * Default : `true`
  59128. */
  59129. set: function (val) {
  59130. this._depthSortParticles = val;
  59131. },
  59132. enumerable: true,
  59133. configurable: true
  59134. });
  59135. // =======================================================================
  59136. // Particle behavior logic
  59137. // these following methods may be overwritten by the user to fit his needs
  59138. /**
  59139. * This function does nothing. It may be overwritten to set all the particle first values.
  59140. * The SPS doesn't call this function, you may have to call it by your own.
  59141. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59142. */
  59143. SolidParticleSystem.prototype.initParticles = function () {
  59144. };
  59145. /**
  59146. * This function does nothing. It may be overwritten to recycle a particle.
  59147. * The SPS doesn't call this function, you may have to call it by your own.
  59148. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59149. * @param particle The particle to recycle
  59150. * @returns the recycled particle
  59151. */
  59152. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59153. return particle;
  59154. };
  59155. /**
  59156. * Updates a particle : this function should be overwritten by the user.
  59157. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59158. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59159. * @example : just set a particle position or velocity and recycle conditions
  59160. * @param particle The particle to update
  59161. * @returns the updated particle
  59162. */
  59163. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59164. return particle;
  59165. };
  59166. /**
  59167. * Updates a vertex of a particle : it can be overwritten by the user.
  59168. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59169. * @param particle the current particle
  59170. * @param vertex the current index of the current particle
  59171. * @param pt the index of the current vertex in the particle shape
  59172. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59173. * @example : just set a vertex particle position
  59174. * @returns the updated vertex
  59175. */
  59176. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59177. return vertex;
  59178. };
  59179. /**
  59180. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59181. * This does nothing and may be overwritten by the user.
  59182. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59183. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59184. * @param update the boolean update value actually passed to setParticles()
  59185. */
  59186. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59187. };
  59188. /**
  59189. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59190. * This will be passed three parameters.
  59191. * This does nothing and may be overwritten by the user.
  59192. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59193. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59194. * @param update the boolean update value actually passed to setParticles()
  59195. */
  59196. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59197. };
  59198. return SolidParticleSystem;
  59199. }());
  59200. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59201. })(BABYLON || (BABYLON = {}));
  59202. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59203. var BABYLON;
  59204. (function (BABYLON) {
  59205. var ShaderMaterial = /** @class */ (function (_super) {
  59206. __extends(ShaderMaterial, _super);
  59207. function ShaderMaterial(name, scene, shaderPath, options) {
  59208. var _this = _super.call(this, name, scene) || this;
  59209. _this._textures = {};
  59210. _this._textureArrays = {};
  59211. _this._floats = {};
  59212. _this._ints = {};
  59213. _this._floatsArrays = {};
  59214. _this._colors3 = {};
  59215. _this._colors3Arrays = {};
  59216. _this._colors4 = {};
  59217. _this._vectors2 = {};
  59218. _this._vectors3 = {};
  59219. _this._vectors4 = {};
  59220. _this._matrices = {};
  59221. _this._matrices3x3 = {};
  59222. _this._matrices2x2 = {};
  59223. _this._vectors2Arrays = {};
  59224. _this._vectors3Arrays = {};
  59225. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59226. _this._shaderPath = shaderPath;
  59227. options.needAlphaBlending = options.needAlphaBlending || false;
  59228. options.needAlphaTesting = options.needAlphaTesting || false;
  59229. options.attributes = options.attributes || ["position", "normal", "uv"];
  59230. options.uniforms = options.uniforms || ["worldViewProjection"];
  59231. options.uniformBuffers = options.uniformBuffers || [];
  59232. options.samplers = options.samplers || [];
  59233. options.defines = options.defines || [];
  59234. _this._options = options;
  59235. return _this;
  59236. }
  59237. ShaderMaterial.prototype.getClassName = function () {
  59238. return "ShaderMaterial";
  59239. };
  59240. ShaderMaterial.prototype.needAlphaBlending = function () {
  59241. return this._options.needAlphaBlending;
  59242. };
  59243. ShaderMaterial.prototype.needAlphaTesting = function () {
  59244. return this._options.needAlphaTesting;
  59245. };
  59246. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59247. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59248. this._options.uniforms.push(uniformName);
  59249. }
  59250. };
  59251. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59252. if (this._options.samplers.indexOf(name) === -1) {
  59253. this._options.samplers.push(name);
  59254. }
  59255. this._textures[name] = texture;
  59256. return this;
  59257. };
  59258. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59259. if (this._options.samplers.indexOf(name) === -1) {
  59260. this._options.samplers.push(name);
  59261. }
  59262. this._checkUniform(name);
  59263. this._textureArrays[name] = textures;
  59264. return this;
  59265. };
  59266. ShaderMaterial.prototype.setFloat = function (name, value) {
  59267. this._checkUniform(name);
  59268. this._floats[name] = value;
  59269. return this;
  59270. };
  59271. ShaderMaterial.prototype.setInt = function (name, value) {
  59272. this._checkUniform(name);
  59273. this._ints[name] = value;
  59274. return this;
  59275. };
  59276. ShaderMaterial.prototype.setFloats = function (name, value) {
  59277. this._checkUniform(name);
  59278. this._floatsArrays[name] = value;
  59279. return this;
  59280. };
  59281. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59282. this._checkUniform(name);
  59283. this._colors3[name] = value;
  59284. return this;
  59285. };
  59286. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59287. this._checkUniform(name);
  59288. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59289. color.toArray(arr, arr.length);
  59290. return arr;
  59291. }, []);
  59292. return this;
  59293. };
  59294. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59295. this._checkUniform(name);
  59296. this._colors4[name] = value;
  59297. return this;
  59298. };
  59299. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59300. this._checkUniform(name);
  59301. this._vectors2[name] = value;
  59302. return this;
  59303. };
  59304. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59305. this._checkUniform(name);
  59306. this._vectors3[name] = value;
  59307. return this;
  59308. };
  59309. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59310. this._checkUniform(name);
  59311. this._vectors4[name] = value;
  59312. return this;
  59313. };
  59314. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59315. this._checkUniform(name);
  59316. this._matrices[name] = value;
  59317. return this;
  59318. };
  59319. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59320. this._checkUniform(name);
  59321. this._matrices3x3[name] = value;
  59322. return this;
  59323. };
  59324. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59325. this._checkUniform(name);
  59326. this._matrices2x2[name] = value;
  59327. return this;
  59328. };
  59329. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59330. this._checkUniform(name);
  59331. this._vectors2Arrays[name] = value;
  59332. return this;
  59333. };
  59334. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59335. this._checkUniform(name);
  59336. this._vectors3Arrays[name] = value;
  59337. return this;
  59338. };
  59339. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59340. if (!mesh) {
  59341. return true;
  59342. }
  59343. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59344. return false;
  59345. }
  59346. return false;
  59347. };
  59348. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59349. var scene = this.getScene();
  59350. var engine = scene.getEngine();
  59351. if (!this.checkReadyOnEveryCall) {
  59352. if (this._renderId === scene.getRenderId()) {
  59353. if (this._checkCache(scene, mesh, useInstances)) {
  59354. return true;
  59355. }
  59356. }
  59357. }
  59358. // Instances
  59359. var defines = [];
  59360. var attribs = [];
  59361. var fallbacks = new BABYLON.EffectFallbacks();
  59362. if (useInstances) {
  59363. defines.push("#define INSTANCES");
  59364. }
  59365. for (var index = 0; index < this._options.defines.length; index++) {
  59366. defines.push(this._options.defines[index]);
  59367. }
  59368. for (var index = 0; index < this._options.attributes.length; index++) {
  59369. attribs.push(this._options.attributes[index]);
  59370. }
  59371. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59372. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59373. defines.push("#define VERTEXCOLOR");
  59374. }
  59375. // Bones
  59376. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59377. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59378. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59379. if (mesh.numBoneInfluencers > 4) {
  59380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59382. }
  59383. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59384. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59385. fallbacks.addCPUSkinningFallback(0, mesh);
  59386. if (this._options.uniforms.indexOf("mBones") === -1) {
  59387. this._options.uniforms.push("mBones");
  59388. }
  59389. }
  59390. else {
  59391. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59392. }
  59393. // Textures
  59394. for (var name in this._textures) {
  59395. if (!this._textures[name].isReady()) {
  59396. return false;
  59397. }
  59398. }
  59399. // Alpha test
  59400. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59401. defines.push("#define ALPHATEST");
  59402. }
  59403. var previousEffect = this._effect;
  59404. var join = defines.join("\n");
  59405. this._effect = engine.createEffect(this._shaderPath, {
  59406. attributes: attribs,
  59407. uniformsNames: this._options.uniforms,
  59408. uniformBuffersNames: this._options.uniformBuffers,
  59409. samplers: this._options.samplers,
  59410. defines: join,
  59411. fallbacks: fallbacks,
  59412. onCompiled: this.onCompiled,
  59413. onError: this.onError
  59414. }, engine);
  59415. if (!this._effect.isReady()) {
  59416. return false;
  59417. }
  59418. if (previousEffect !== this._effect) {
  59419. scene.resetCachedMaterial();
  59420. }
  59421. this._renderId = scene.getRenderId();
  59422. return true;
  59423. };
  59424. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59425. var scene = this.getScene();
  59426. if (!this._effect) {
  59427. return;
  59428. }
  59429. if (this._options.uniforms.indexOf("world") !== -1) {
  59430. this._effect.setMatrix("world", world);
  59431. }
  59432. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59433. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59434. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59435. }
  59436. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59437. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59438. }
  59439. };
  59440. ShaderMaterial.prototype.bind = function (world, mesh) {
  59441. // Std values
  59442. this.bindOnlyWorldMatrix(world);
  59443. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59444. if (this._options.uniforms.indexOf("view") !== -1) {
  59445. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59446. }
  59447. if (this._options.uniforms.indexOf("projection") !== -1) {
  59448. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59449. }
  59450. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59451. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59452. }
  59453. // Bones
  59454. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59455. var name;
  59456. // Texture
  59457. for (name in this._textures) {
  59458. this._effect.setTexture(name, this._textures[name]);
  59459. }
  59460. // Texture arrays
  59461. for (name in this._textureArrays) {
  59462. this._effect.setTextureArray(name, this._textureArrays[name]);
  59463. }
  59464. // Int
  59465. for (name in this._ints) {
  59466. this._effect.setInt(name, this._ints[name]);
  59467. }
  59468. // Float
  59469. for (name in this._floats) {
  59470. this._effect.setFloat(name, this._floats[name]);
  59471. }
  59472. // Floats
  59473. for (name in this._floatsArrays) {
  59474. this._effect.setArray(name, this._floatsArrays[name]);
  59475. }
  59476. // Color3
  59477. for (name in this._colors3) {
  59478. this._effect.setColor3(name, this._colors3[name]);
  59479. }
  59480. for (name in this._colors3Arrays) {
  59481. this._effect.setArray3(name, this._colors3Arrays[name]);
  59482. }
  59483. // Color4
  59484. for (name in this._colors4) {
  59485. var color = this._colors4[name];
  59486. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59487. }
  59488. // Vector2
  59489. for (name in this._vectors2) {
  59490. this._effect.setVector2(name, this._vectors2[name]);
  59491. }
  59492. // Vector3
  59493. for (name in this._vectors3) {
  59494. this._effect.setVector3(name, this._vectors3[name]);
  59495. }
  59496. // Vector4
  59497. for (name in this._vectors4) {
  59498. this._effect.setVector4(name, this._vectors4[name]);
  59499. }
  59500. // Matrix
  59501. for (name in this._matrices) {
  59502. this._effect.setMatrix(name, this._matrices[name]);
  59503. }
  59504. // Matrix 3x3
  59505. for (name in this._matrices3x3) {
  59506. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59507. }
  59508. // Matrix 2x2
  59509. for (name in this._matrices2x2) {
  59510. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59511. }
  59512. // Vector2Array
  59513. for (name in this._vectors2Arrays) {
  59514. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59515. }
  59516. // Vector3Array
  59517. for (name in this._vectors3Arrays) {
  59518. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59519. }
  59520. }
  59521. this._afterBind(mesh);
  59522. };
  59523. ShaderMaterial.prototype.getActiveTextures = function () {
  59524. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59525. for (var name in this._textures) {
  59526. activeTextures.push(this._textures[name]);
  59527. }
  59528. for (var name in this._textureArrays) {
  59529. var array = this._textureArrays[name];
  59530. for (var index = 0; index < array.length; index++) {
  59531. activeTextures.push(array[index]);
  59532. }
  59533. }
  59534. return activeTextures;
  59535. };
  59536. ShaderMaterial.prototype.hasTexture = function (texture) {
  59537. if (_super.prototype.hasTexture.call(this, texture)) {
  59538. return true;
  59539. }
  59540. for (var name in this._textures) {
  59541. if (this._textures[name] === texture) {
  59542. return true;
  59543. }
  59544. }
  59545. for (var name in this._textureArrays) {
  59546. var array = this._textureArrays[name];
  59547. for (var index = 0; index < array.length; index++) {
  59548. if (array[index] === texture) {
  59549. return true;
  59550. }
  59551. }
  59552. }
  59553. return false;
  59554. };
  59555. ShaderMaterial.prototype.clone = function (name) {
  59556. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59557. return newShaderMaterial;
  59558. };
  59559. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59560. if (forceDisposeTextures) {
  59561. var name;
  59562. for (name in this._textures) {
  59563. this._textures[name].dispose();
  59564. }
  59565. for (name in this._textureArrays) {
  59566. var array = this._textureArrays[name];
  59567. for (var index = 0; index < array.length; index++) {
  59568. array[index].dispose();
  59569. }
  59570. }
  59571. }
  59572. this._textures = {};
  59573. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59574. };
  59575. ShaderMaterial.prototype.serialize = function () {
  59576. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59577. serializationObject.customType = "BABYLON.ShaderMaterial";
  59578. serializationObject.options = this._options;
  59579. serializationObject.shaderPath = this._shaderPath;
  59580. var name;
  59581. // Texture
  59582. serializationObject.textures = {};
  59583. for (name in this._textures) {
  59584. serializationObject.textures[name] = this._textures[name].serialize();
  59585. }
  59586. // Texture arrays
  59587. serializationObject.textureArrays = {};
  59588. for (name in this._textureArrays) {
  59589. serializationObject.textureArrays[name] = [];
  59590. var array = this._textureArrays[name];
  59591. for (var index = 0; index < array.length; index++) {
  59592. serializationObject.textureArrays[name].push(array[index].serialize());
  59593. }
  59594. }
  59595. // Float
  59596. serializationObject.floats = {};
  59597. for (name in this._floats) {
  59598. serializationObject.floats[name] = this._floats[name];
  59599. }
  59600. // Float s
  59601. serializationObject.FloatArrays = {};
  59602. for (name in this._floatsArrays) {
  59603. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59604. }
  59605. // Color3
  59606. serializationObject.colors3 = {};
  59607. for (name in this._colors3) {
  59608. serializationObject.colors3[name] = this._colors3[name].asArray();
  59609. }
  59610. // Color3 array
  59611. serializationObject.colors3Arrays = {};
  59612. for (name in this._colors3Arrays) {
  59613. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59614. }
  59615. // Color4
  59616. serializationObject.colors4 = {};
  59617. for (name in this._colors4) {
  59618. serializationObject.colors4[name] = this._colors4[name].asArray();
  59619. }
  59620. // Vector2
  59621. serializationObject.vectors2 = {};
  59622. for (name in this._vectors2) {
  59623. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59624. }
  59625. // Vector3
  59626. serializationObject.vectors3 = {};
  59627. for (name in this._vectors3) {
  59628. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59629. }
  59630. // Vector4
  59631. serializationObject.vectors4 = {};
  59632. for (name in this._vectors4) {
  59633. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59634. }
  59635. // Matrix
  59636. serializationObject.matrices = {};
  59637. for (name in this._matrices) {
  59638. serializationObject.matrices[name] = this._matrices[name].asArray();
  59639. }
  59640. // Matrix 3x3
  59641. serializationObject.matrices3x3 = {};
  59642. for (name in this._matrices3x3) {
  59643. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59644. }
  59645. // Matrix 2x2
  59646. serializationObject.matrices2x2 = {};
  59647. for (name in this._matrices2x2) {
  59648. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59649. }
  59650. // Vector2Array
  59651. serializationObject.vectors2Arrays = {};
  59652. for (name in this._vectors2Arrays) {
  59653. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59654. }
  59655. // Vector3Array
  59656. serializationObject.vectors3Arrays = {};
  59657. for (name in this._vectors3Arrays) {
  59658. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59659. }
  59660. return serializationObject;
  59661. };
  59662. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59663. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59664. var name;
  59665. // Texture
  59666. for (name in source.textures) {
  59667. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59668. }
  59669. // Texture arrays
  59670. for (name in source.textureArrays) {
  59671. var array = source.textureArrays[name];
  59672. var textureArray = new Array();
  59673. for (var index = 0; index < array.length; index++) {
  59674. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59675. }
  59676. material.setTextureArray(name, textureArray);
  59677. }
  59678. // Float
  59679. for (name in source.floats) {
  59680. material.setFloat(name, source.floats[name]);
  59681. }
  59682. // Float s
  59683. for (name in source.floatsArrays) {
  59684. material.setFloats(name, source.floatsArrays[name]);
  59685. }
  59686. // Color3
  59687. for (name in source.colors3) {
  59688. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59689. }
  59690. // Color3 arrays
  59691. for (name in source.colors3Arrays) {
  59692. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59693. if (i % 3 === 0) {
  59694. arr.push([num]);
  59695. }
  59696. else {
  59697. arr[arr.length - 1].push(num);
  59698. }
  59699. return arr;
  59700. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59701. material.setColor3Array(name, colors);
  59702. }
  59703. // Color4
  59704. for (name in source.colors4) {
  59705. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59706. }
  59707. // Vector2
  59708. for (name in source.vectors2) {
  59709. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59710. }
  59711. // Vector3
  59712. for (name in source.vectors3) {
  59713. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59714. }
  59715. // Vector4
  59716. for (name in source.vectors4) {
  59717. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59718. }
  59719. // Matrix
  59720. for (name in source.matrices) {
  59721. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59722. }
  59723. // Matrix 3x3
  59724. for (name in source.matrices3x3) {
  59725. material.setMatrix3x3(name, source.matrices3x3[name]);
  59726. }
  59727. // Matrix 2x2
  59728. for (name in source.matrices2x2) {
  59729. material.setMatrix2x2(name, source.matrices2x2[name]);
  59730. }
  59731. // Vector2Array
  59732. for (name in source.vectors2Arrays) {
  59733. material.setArray2(name, source.vectors2Arrays[name]);
  59734. }
  59735. // Vector3Array
  59736. for (name in source.vectors3Arrays) {
  59737. material.setArray3(name, source.vectors3Arrays[name]);
  59738. }
  59739. return material;
  59740. };
  59741. return ShaderMaterial;
  59742. }(BABYLON.Material));
  59743. BABYLON.ShaderMaterial = ShaderMaterial;
  59744. })(BABYLON || (BABYLON = {}));
  59745. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59746. var BABYLON;
  59747. (function (BABYLON) {
  59748. var GroundMesh = /** @class */ (function (_super) {
  59749. __extends(GroundMesh, _super);
  59750. function GroundMesh(name, scene) {
  59751. var _this = _super.call(this, name, scene) || this;
  59752. _this.generateOctree = false;
  59753. return _this;
  59754. }
  59755. GroundMesh.prototype.getClassName = function () {
  59756. return "GroundMesh";
  59757. };
  59758. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59759. get: function () {
  59760. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59761. },
  59762. enumerable: true,
  59763. configurable: true
  59764. });
  59765. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59766. get: function () {
  59767. return this._subdivisionsX;
  59768. },
  59769. enumerable: true,
  59770. configurable: true
  59771. });
  59772. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59773. get: function () {
  59774. return this._subdivisionsY;
  59775. },
  59776. enumerable: true,
  59777. configurable: true
  59778. });
  59779. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59780. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59781. this._subdivisionsX = chunksCount;
  59782. this._subdivisionsY = chunksCount;
  59783. this.subdivide(chunksCount);
  59784. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59785. };
  59786. /**
  59787. * Returns a height (y) value in the Worl system :
  59788. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59789. * Returns the ground y position if (x, z) are outside the ground surface.
  59790. */
  59791. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59792. var world = this.getWorldMatrix();
  59793. var invMat = BABYLON.Tmp.Matrix[5];
  59794. world.invertToRef(invMat);
  59795. var tmpVect = BABYLON.Tmp.Vector3[8];
  59796. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59797. x = tmpVect.x;
  59798. z = tmpVect.z;
  59799. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59800. return this.position.y;
  59801. }
  59802. if (!this._heightQuads || this._heightQuads.length == 0) {
  59803. this._initHeightQuads();
  59804. this._computeHeightQuads();
  59805. }
  59806. var facet = this._getFacetAt(x, z);
  59807. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59808. // return y in the World system
  59809. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59810. return tmpVect.y;
  59811. };
  59812. /**
  59813. * Returns a normalized vector (Vector3) orthogonal to the ground
  59814. * at the ground coordinates (x, z) expressed in the World system.
  59815. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59816. */
  59817. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59818. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59819. this.getNormalAtCoordinatesToRef(x, z, normal);
  59820. return normal;
  59821. };
  59822. /**
  59823. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59824. * at the ground coordinates (x, z) expressed in the World system.
  59825. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59826. * Returns the GroundMesh.
  59827. */
  59828. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59829. var world = this.getWorldMatrix();
  59830. var tmpMat = BABYLON.Tmp.Matrix[5];
  59831. world.invertToRef(tmpMat);
  59832. var tmpVect = BABYLON.Tmp.Vector3[8];
  59833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59834. x = tmpVect.x;
  59835. z = tmpVect.z;
  59836. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59837. return this;
  59838. }
  59839. if (!this._heightQuads || this._heightQuads.length == 0) {
  59840. this._initHeightQuads();
  59841. this._computeHeightQuads();
  59842. }
  59843. var facet = this._getFacetAt(x, z);
  59844. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59845. return this;
  59846. };
  59847. /**
  59848. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59849. * if the ground has been updated.
  59850. * This can be used in the render loop.
  59851. * Returns the GroundMesh.
  59852. */
  59853. GroundMesh.prototype.updateCoordinateHeights = function () {
  59854. if (!this._heightQuads || this._heightQuads.length == 0) {
  59855. this._initHeightQuads();
  59856. }
  59857. this._computeHeightQuads();
  59858. return this;
  59859. };
  59860. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59861. GroundMesh.prototype._getFacetAt = function (x, z) {
  59862. // retrieve col and row from x, z coordinates in the ground local system
  59863. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59864. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59865. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59866. var facet;
  59867. if (z < quad.slope.x * x + quad.slope.y) {
  59868. facet = quad.facet1;
  59869. }
  59870. else {
  59871. facet = quad.facet2;
  59872. }
  59873. return facet;
  59874. };
  59875. // Creates and populates the heightMap array with "facet" elements :
  59876. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59877. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59878. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59879. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59880. // Returns the GroundMesh.
  59881. GroundMesh.prototype._initHeightQuads = function () {
  59882. var subdivisionsX = this._subdivisionsX;
  59883. var subdivisionsY = this._subdivisionsY;
  59884. this._heightQuads = new Array();
  59885. for (var row = 0; row < subdivisionsY; row++) {
  59886. for (var col = 0; col < subdivisionsX; col++) {
  59887. 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) };
  59888. this._heightQuads[row * subdivisionsX + col] = quad;
  59889. }
  59890. }
  59891. return this;
  59892. };
  59893. // Compute each quad element values and update the the heightMap array :
  59894. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59895. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59896. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59897. // Returns the GroundMesh.
  59898. GroundMesh.prototype._computeHeightQuads = function () {
  59899. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59900. if (!positions) {
  59901. return this;
  59902. }
  59903. var v1 = BABYLON.Tmp.Vector3[3];
  59904. var v2 = BABYLON.Tmp.Vector3[2];
  59905. var v3 = BABYLON.Tmp.Vector3[1];
  59906. var v4 = BABYLON.Tmp.Vector3[0];
  59907. var v1v2 = BABYLON.Tmp.Vector3[4];
  59908. var v1v3 = BABYLON.Tmp.Vector3[5];
  59909. var v1v4 = BABYLON.Tmp.Vector3[6];
  59910. var norm1 = BABYLON.Tmp.Vector3[7];
  59911. var norm2 = BABYLON.Tmp.Vector3[8];
  59912. var i = 0;
  59913. var j = 0;
  59914. var k = 0;
  59915. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59916. var h = 0;
  59917. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59918. var d2 = 0;
  59919. var subdivisionsX = this._subdivisionsX;
  59920. var subdivisionsY = this._subdivisionsY;
  59921. for (var row = 0; row < subdivisionsY; row++) {
  59922. for (var col = 0; col < subdivisionsX; col++) {
  59923. i = col * 3;
  59924. j = row * (subdivisionsX + 1) * 3;
  59925. k = (row + 1) * (subdivisionsX + 1) * 3;
  59926. v1.x = positions[j + i];
  59927. v1.y = positions[j + i + 1];
  59928. v1.z = positions[j + i + 2];
  59929. v2.x = positions[j + i + 3];
  59930. v2.y = positions[j + i + 4];
  59931. v2.z = positions[j + i + 5];
  59932. v3.x = positions[k + i];
  59933. v3.y = positions[k + i + 1];
  59934. v3.z = positions[k + i + 2];
  59935. v4.x = positions[k + i + 3];
  59936. v4.y = positions[k + i + 4];
  59937. v4.z = positions[k + i + 5];
  59938. // 2D slope V1V4
  59939. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59940. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59941. // facet equations :
  59942. // we compute each facet normal vector
  59943. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59944. // we compute the value d by applying the equation to v1 which belongs to the plane
  59945. // then we store the facet equation in a Vector4
  59946. v2.subtractToRef(v1, v1v2);
  59947. v3.subtractToRef(v1, v1v3);
  59948. v4.subtractToRef(v1, v1v4);
  59949. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59950. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59951. norm1.normalize();
  59952. norm2.normalize();
  59953. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59954. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59955. var quad = this._heightQuads[row * subdivisionsX + col];
  59956. quad.slope.copyFromFloats(cd, h);
  59957. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59958. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59959. }
  59960. }
  59961. return this;
  59962. };
  59963. GroundMesh.prototype.serialize = function (serializationObject) {
  59964. _super.prototype.serialize.call(this, serializationObject);
  59965. serializationObject.subdivisionsX = this._subdivisionsX;
  59966. serializationObject.subdivisionsY = this._subdivisionsY;
  59967. serializationObject.minX = this._minX;
  59968. serializationObject.maxX = this._maxX;
  59969. serializationObject.minZ = this._minZ;
  59970. serializationObject.maxZ = this._maxZ;
  59971. serializationObject.width = this._width;
  59972. serializationObject.height = this._height;
  59973. };
  59974. GroundMesh.Parse = function (parsedMesh, scene) {
  59975. var result = new GroundMesh(parsedMesh.name, scene);
  59976. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59977. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59978. result._minX = parsedMesh.minX;
  59979. result._maxX = parsedMesh.maxX;
  59980. result._minZ = parsedMesh.minZ;
  59981. result._maxZ = parsedMesh.maxZ;
  59982. result._width = parsedMesh.width;
  59983. result._height = parsedMesh.height;
  59984. return result;
  59985. };
  59986. return GroundMesh;
  59987. }(BABYLON.Mesh));
  59988. BABYLON.GroundMesh = GroundMesh;
  59989. })(BABYLON || (BABYLON = {}));
  59990. //# sourceMappingURL=babylon.groundMesh.js.map
  59991. var BABYLON;
  59992. (function (BABYLON) {
  59993. /**
  59994. * Creates an instance based on a source mesh.
  59995. */
  59996. var InstancedMesh = /** @class */ (function (_super) {
  59997. __extends(InstancedMesh, _super);
  59998. function InstancedMesh(name, source) {
  59999. var _this = _super.call(this, name, source.getScene()) || this;
  60000. source.instances.push(_this);
  60001. _this._sourceMesh = source;
  60002. _this.position.copyFrom(source.position);
  60003. _this.rotation.copyFrom(source.rotation);
  60004. _this.scaling.copyFrom(source.scaling);
  60005. if (source.rotationQuaternion) {
  60006. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60007. }
  60008. _this.infiniteDistance = source.infiniteDistance;
  60009. _this.setPivotMatrix(source.getPivotMatrix());
  60010. _this.refreshBoundingInfo();
  60011. _this._syncSubMeshes();
  60012. return _this;
  60013. }
  60014. /**
  60015. * Returns the string "InstancedMesh".
  60016. */
  60017. InstancedMesh.prototype.getClassName = function () {
  60018. return "InstancedMesh";
  60019. };
  60020. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60021. // Methods
  60022. get: function () {
  60023. return this._sourceMesh.receiveShadows;
  60024. },
  60025. enumerable: true,
  60026. configurable: true
  60027. });
  60028. Object.defineProperty(InstancedMesh.prototype, "material", {
  60029. get: function () {
  60030. return this._sourceMesh.material;
  60031. },
  60032. enumerable: true,
  60033. configurable: true
  60034. });
  60035. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60036. get: function () {
  60037. return this._sourceMesh.visibility;
  60038. },
  60039. enumerable: true,
  60040. configurable: true
  60041. });
  60042. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60043. get: function () {
  60044. return this._sourceMesh.skeleton;
  60045. },
  60046. enumerable: true,
  60047. configurable: true
  60048. });
  60049. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60050. get: function () {
  60051. return this._sourceMesh.renderingGroupId;
  60052. },
  60053. set: function (value) {
  60054. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60055. return;
  60056. }
  60057. //no-op with warning
  60058. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60059. },
  60060. enumerable: true,
  60061. configurable: true
  60062. });
  60063. /**
  60064. * Returns the total number of vertices (integer).
  60065. */
  60066. InstancedMesh.prototype.getTotalVertices = function () {
  60067. return this._sourceMesh.getTotalVertices();
  60068. };
  60069. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60070. get: function () {
  60071. return this._sourceMesh;
  60072. },
  60073. enumerable: true,
  60074. configurable: true
  60075. });
  60076. /**
  60077. * Is this node ready to be used/rendered
  60078. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60079. * @return {boolean} is it ready
  60080. */
  60081. InstancedMesh.prototype.isReady = function (completeCheck) {
  60082. if (completeCheck === void 0) { completeCheck = false; }
  60083. return this._sourceMesh.isReady(completeCheck, true);
  60084. };
  60085. /**
  60086. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60087. */
  60088. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60089. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60090. };
  60091. /**
  60092. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60093. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60094. * The `data` are either a numeric array either a Float32Array.
  60095. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60096. * 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).
  60097. * Note that a new underlying VertexBuffer object is created each call.
  60098. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60099. *
  60100. * Possible `kind` values :
  60101. * - BABYLON.VertexBuffer.PositionKind
  60102. * - BABYLON.VertexBuffer.UVKind
  60103. * - BABYLON.VertexBuffer.UV2Kind
  60104. * - BABYLON.VertexBuffer.UV3Kind
  60105. * - BABYLON.VertexBuffer.UV4Kind
  60106. * - BABYLON.VertexBuffer.UV5Kind
  60107. * - BABYLON.VertexBuffer.UV6Kind
  60108. * - BABYLON.VertexBuffer.ColorKind
  60109. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60110. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60111. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60112. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60113. *
  60114. * Returns the Mesh.
  60115. */
  60116. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60117. if (this.sourceMesh) {
  60118. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60119. }
  60120. return this.sourceMesh;
  60121. };
  60122. /**
  60123. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60124. * If the mesh has no geometry, it is simply returned as it is.
  60125. * The `data` are either a numeric array either a Float32Array.
  60126. * No new underlying VertexBuffer object is created.
  60127. * 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.
  60128. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60129. *
  60130. * Possible `kind` values :
  60131. * - BABYLON.VertexBuffer.PositionKind
  60132. * - BABYLON.VertexBuffer.UVKind
  60133. * - BABYLON.VertexBuffer.UV2Kind
  60134. * - BABYLON.VertexBuffer.UV3Kind
  60135. * - BABYLON.VertexBuffer.UV4Kind
  60136. * - BABYLON.VertexBuffer.UV5Kind
  60137. * - BABYLON.VertexBuffer.UV6Kind
  60138. * - BABYLON.VertexBuffer.ColorKind
  60139. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60140. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60141. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60142. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60143. *
  60144. * Returns the Mesh.
  60145. */
  60146. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60147. if (this.sourceMesh) {
  60148. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60149. }
  60150. return this.sourceMesh;
  60151. };
  60152. /**
  60153. * Sets the mesh indices.
  60154. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60155. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60156. * This method creates a new index buffer each call.
  60157. * Returns the Mesh.
  60158. */
  60159. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60160. if (totalVertices === void 0) { totalVertices = null; }
  60161. if (this.sourceMesh) {
  60162. this.sourceMesh.setIndices(indices, totalVertices);
  60163. }
  60164. return this.sourceMesh;
  60165. };
  60166. /**
  60167. * Boolean : True if the mesh owns the requested kind of data.
  60168. */
  60169. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60170. return this._sourceMesh.isVerticesDataPresent(kind);
  60171. };
  60172. /**
  60173. * Returns an array of indices (IndicesArray).
  60174. */
  60175. InstancedMesh.prototype.getIndices = function () {
  60176. return this._sourceMesh.getIndices();
  60177. };
  60178. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60179. get: function () {
  60180. return this._sourceMesh._positions;
  60181. },
  60182. enumerable: true,
  60183. configurable: true
  60184. });
  60185. /**
  60186. * Sets a new updated BoundingInfo to the mesh.
  60187. * Returns the mesh.
  60188. */
  60189. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60190. var meshBB = this._sourceMesh.getBoundingInfo();
  60191. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60192. this._updateBoundingInfo();
  60193. return this;
  60194. };
  60195. InstancedMesh.prototype._preActivate = function () {
  60196. if (this._currentLOD) {
  60197. this._currentLOD._preActivate();
  60198. }
  60199. return this;
  60200. };
  60201. InstancedMesh.prototype._activate = function (renderId) {
  60202. if (this._currentLOD) {
  60203. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60204. }
  60205. return this;
  60206. };
  60207. /**
  60208. * Returns the current associated LOD AbstractMesh.
  60209. */
  60210. InstancedMesh.prototype.getLOD = function (camera) {
  60211. if (!camera) {
  60212. return this;
  60213. }
  60214. var boundingInfo = this.getBoundingInfo();
  60215. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60216. if (this._currentLOD === this.sourceMesh) {
  60217. return this;
  60218. }
  60219. return this._currentLOD;
  60220. };
  60221. InstancedMesh.prototype._syncSubMeshes = function () {
  60222. this.releaseSubMeshes();
  60223. if (this._sourceMesh.subMeshes) {
  60224. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60225. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60226. }
  60227. }
  60228. return this;
  60229. };
  60230. InstancedMesh.prototype._generatePointsArray = function () {
  60231. return this._sourceMesh._generatePointsArray();
  60232. };
  60233. /**
  60234. * Creates a new InstancedMesh from the current mesh.
  60235. * - name (string) : the cloned mesh name
  60236. * - newParent (optional Node) : the optional Node to parent the clone to.
  60237. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60238. *
  60239. * Returns the clone.
  60240. */
  60241. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60242. var result = this._sourceMesh.createInstance(name);
  60243. // Deep copy
  60244. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60245. // Bounding info
  60246. this.refreshBoundingInfo();
  60247. // Parent
  60248. if (newParent) {
  60249. result.parent = newParent;
  60250. }
  60251. if (!doNotCloneChildren) {
  60252. // Children
  60253. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60254. var mesh = this.getScene().meshes[index];
  60255. if (mesh.parent === this) {
  60256. mesh.clone(mesh.name, result);
  60257. }
  60258. }
  60259. }
  60260. result.computeWorldMatrix(true);
  60261. return result;
  60262. };
  60263. /**
  60264. * Disposes the InstancedMesh.
  60265. * Returns nothing.
  60266. */
  60267. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60268. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60269. // Remove from mesh
  60270. var index = this._sourceMesh.instances.indexOf(this);
  60271. this._sourceMesh.instances.splice(index, 1);
  60272. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60273. };
  60274. return InstancedMesh;
  60275. }(BABYLON.AbstractMesh));
  60276. BABYLON.InstancedMesh = InstancedMesh;
  60277. })(BABYLON || (BABYLON = {}));
  60278. //# sourceMappingURL=babylon.instancedMesh.js.map
  60279. var BABYLON;
  60280. (function (BABYLON) {
  60281. var LinesMesh = /** @class */ (function (_super) {
  60282. __extends(LinesMesh, _super);
  60283. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60284. if (scene === void 0) { scene = null; }
  60285. if (parent === void 0) { parent = null; }
  60286. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60287. _this.useVertexColor = useVertexColor;
  60288. _this.useVertexAlpha = useVertexAlpha;
  60289. _this.color = new BABYLON.Color3(1, 1, 1);
  60290. _this.alpha = 1;
  60291. if (source) {
  60292. _this.color = source.color.clone();
  60293. _this.alpha = source.alpha;
  60294. _this.useVertexColor = source.useVertexColor;
  60295. _this.useVertexAlpha = source.useVertexAlpha;
  60296. }
  60297. _this._intersectionThreshold = 0.1;
  60298. var defines = [];
  60299. var options = {
  60300. attributes: [BABYLON.VertexBuffer.PositionKind],
  60301. uniforms: ["world", "viewProjection"],
  60302. needAlphaBlending: true,
  60303. defines: defines
  60304. };
  60305. if (useVertexAlpha === false) {
  60306. options.needAlphaBlending = false;
  60307. }
  60308. if (!useVertexColor) {
  60309. options.uniforms.push("color");
  60310. }
  60311. else {
  60312. options.defines.push("#define VERTEXCOLOR");
  60313. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60314. }
  60315. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60316. return _this;
  60317. }
  60318. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60319. /**
  60320. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60321. * This margin is expressed in world space coordinates, so its value may vary.
  60322. * Default value is 0.1
  60323. * @returns the intersection Threshold value.
  60324. */
  60325. get: function () {
  60326. return this._intersectionThreshold;
  60327. },
  60328. /**
  60329. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60330. * This margin is expressed in world space coordinates, so its value may vary.
  60331. * @param value the new threshold to apply
  60332. */
  60333. set: function (value) {
  60334. if (this._intersectionThreshold === value) {
  60335. return;
  60336. }
  60337. this._intersectionThreshold = value;
  60338. if (this.geometry) {
  60339. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60340. }
  60341. },
  60342. enumerable: true,
  60343. configurable: true
  60344. });
  60345. /**
  60346. * Returns the string "LineMesh"
  60347. */
  60348. LinesMesh.prototype.getClassName = function () {
  60349. return "LinesMesh";
  60350. };
  60351. Object.defineProperty(LinesMesh.prototype, "material", {
  60352. get: function () {
  60353. return this._colorShader;
  60354. },
  60355. set: function (value) {
  60356. // Do nothing
  60357. },
  60358. enumerable: true,
  60359. configurable: true
  60360. });
  60361. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60362. get: function () {
  60363. return false;
  60364. },
  60365. enumerable: true,
  60366. configurable: true
  60367. });
  60368. LinesMesh.prototype.createInstance = function (name) {
  60369. throw new Error("LinesMeshes do not support createInstance.");
  60370. };
  60371. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60372. if (!this._geometry) {
  60373. return this;
  60374. }
  60375. // VBOs
  60376. this._geometry._bind(this._colorShader.getEffect());
  60377. // Color
  60378. if (!this.useVertexColor) {
  60379. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60380. }
  60381. return this;
  60382. };
  60383. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60384. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60385. return this;
  60386. }
  60387. var engine = this.getScene().getEngine();
  60388. // Draw order
  60389. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60390. return this;
  60391. };
  60392. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60393. this._colorShader.dispose();
  60394. _super.prototype.dispose.call(this, doNotRecurse);
  60395. };
  60396. /**
  60397. * Returns a new LineMesh object cloned from the current one.
  60398. */
  60399. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60400. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60401. };
  60402. return LinesMesh;
  60403. }(BABYLON.Mesh));
  60404. BABYLON.LinesMesh = LinesMesh;
  60405. })(BABYLON || (BABYLON = {}));
  60406. //# sourceMappingURL=babylon.linesMesh.js.map
  60407. var BABYLON;
  60408. (function (BABYLON) {
  60409. /**
  60410. * Class containing static functions to help procedurally build meshes
  60411. */
  60412. var MeshBuilder = /** @class */ (function () {
  60413. function MeshBuilder() {
  60414. }
  60415. MeshBuilder.updateSideOrientation = function (orientation) {
  60416. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60417. return BABYLON.Mesh.DOUBLESIDE;
  60418. }
  60419. if (orientation === undefined || orientation === null) {
  60420. return BABYLON.Mesh.FRONTSIDE;
  60421. }
  60422. return orientation;
  60423. };
  60424. /**
  60425. * Creates a box mesh
  60426. * * The parameter `size` sets the size (float) of each box side (default 1)
  60427. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60428. * * 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)
  60429. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60430. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60431. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60432. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60433. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60434. * @param name defines the name of the mesh
  60435. * @param options defines the options used to create the mesh
  60436. * @param scene defines the hosting scene
  60437. * @returns the box mesh
  60438. */
  60439. MeshBuilder.CreateBox = function (name, options, scene) {
  60440. if (scene === void 0) { scene = null; }
  60441. var box = new BABYLON.Mesh(name, scene);
  60442. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60443. box._originalBuilderSideOrientation = options.sideOrientation;
  60444. var vertexData = BABYLON.VertexData.CreateBox(options);
  60445. vertexData.applyToMesh(box, options.updatable);
  60446. return box;
  60447. };
  60448. /**
  60449. * Creates a sphere mesh
  60450. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60451. * * 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`)
  60452. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60453. * * 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
  60454. * * 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)
  60455. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60456. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60457. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60458. * @param name defines the name of the mesh
  60459. * @param options defines the options used to create the mesh
  60460. * @param scene defines the hosting scene
  60461. * @returns the sphere mesh
  60462. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60463. */
  60464. MeshBuilder.CreateSphere = function (name, options, scene) {
  60465. var sphere = new BABYLON.Mesh(name, scene);
  60466. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60467. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60468. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60469. vertexData.applyToMesh(sphere, options.updatable);
  60470. return sphere;
  60471. };
  60472. /**
  60473. * Creates a plane polygonal mesh. By default, this is a disc
  60474. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60475. * * 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
  60476. * * 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
  60477. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60478. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60479. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60480. * @param name defines the name of the mesh
  60481. * @param options defines the options used to create the mesh
  60482. * @param scene defines the hosting scene
  60483. * @returns the plane polygonal mesh
  60484. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60485. */
  60486. MeshBuilder.CreateDisc = function (name, options, scene) {
  60487. if (scene === void 0) { scene = null; }
  60488. var disc = new BABYLON.Mesh(name, scene);
  60489. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60490. disc._originalBuilderSideOrientation = options.sideOrientation;
  60491. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60492. vertexData.applyToMesh(disc, options.updatable);
  60493. return disc;
  60494. };
  60495. /**
  60496. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60497. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60498. * * 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`)
  60499. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60500. * * 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
  60501. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60502. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60503. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60504. * @param name defines the name of the mesh
  60505. * @param options defines the options used to create the mesh
  60506. * @param scene defines the hosting scene
  60507. * @returns the icosahedron mesh
  60508. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60509. */
  60510. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60511. var sphere = new BABYLON.Mesh(name, scene);
  60512. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60513. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60514. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60515. vertexData.applyToMesh(sphere, options.updatable);
  60516. return sphere;
  60517. };
  60518. ;
  60519. /**
  60520. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60521. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60522. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60523. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60524. * * 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
  60525. * * 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
  60526. * * 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
  60527. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60528. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60529. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60530. * * 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
  60531. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60532. * * 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 if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60533. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60534. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60535. * @param name defines the name of the mesh
  60536. * @param options defines the options used to create the mesh
  60537. * @param scene defines the hosting scene
  60538. * @returns the ribbon mesh
  60539. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60540. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60541. */
  60542. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60543. if (scene === void 0) { scene = null; }
  60544. var pathArray = options.pathArray;
  60545. var closeArray = options.closeArray;
  60546. var closePath = options.closePath;
  60547. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60548. var instance = options.instance;
  60549. var updatable = options.updatable;
  60550. if (instance) { // existing ribbon instance update
  60551. // positionFunction : ribbon case
  60552. // only pathArray and sideOrientation parameters are taken into account for positions update
  60553. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60554. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60555. var positionFunction = function (positions) {
  60556. var minlg = pathArray[0].length;
  60557. var i = 0;
  60558. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60559. for (var si = 1; si <= ns; si++) {
  60560. for (var p = 0; p < pathArray.length; p++) {
  60561. var path = pathArray[p];
  60562. var l = path.length;
  60563. minlg = (minlg < l) ? minlg : l;
  60564. var j = 0;
  60565. while (j < minlg) {
  60566. positions[i] = path[j].x;
  60567. positions[i + 1] = path[j].y;
  60568. positions[i + 2] = path[j].z;
  60569. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60570. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60571. }
  60572. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60573. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60574. }
  60575. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60576. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60577. }
  60578. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60579. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60580. }
  60581. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60582. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60583. }
  60584. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60585. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60586. }
  60587. j++;
  60588. i += 3;
  60589. }
  60590. if (instance._closePath) {
  60591. positions[i] = path[0].x;
  60592. positions[i + 1] = path[0].y;
  60593. positions[i + 2] = path[0].z;
  60594. i += 3;
  60595. }
  60596. }
  60597. }
  60598. };
  60599. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60600. positionFunction(positions);
  60601. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60602. instance._boundingInfo.update(instance._worldMatrix);
  60603. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60604. if (options.colors) {
  60605. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60606. for (var c = 0; c < options.colors.length; c++) {
  60607. colors[c * 4] = options.colors[c].r;
  60608. colors[c * 4 + 1] = options.colors[c].g;
  60609. colors[c * 4 + 2] = options.colors[c].b;
  60610. colors[c * 4 + 3] = options.colors[c].a;
  60611. }
  60612. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60613. }
  60614. if (options.uvs) {
  60615. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60616. for (var i = 0; i < options.uvs.length; i++) {
  60617. uvs[i * 2] = options.uvs[i].x;
  60618. uvs[i * 2 + 1] = options.uvs[i].y;
  60619. }
  60620. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60621. }
  60622. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60623. var indices = instance.getIndices();
  60624. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60625. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60626. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60627. if (instance._closePath) {
  60628. var indexFirst = 0;
  60629. var indexLast = 0;
  60630. for (var p = 0; p < pathArray.length; p++) {
  60631. indexFirst = instance._idx[p] * 3;
  60632. if (p + 1 < pathArray.length) {
  60633. indexLast = (instance._idx[p + 1] - 1) * 3;
  60634. }
  60635. else {
  60636. indexLast = normals.length - 3;
  60637. }
  60638. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60639. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60640. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60641. normals[indexLast] = normals[indexFirst];
  60642. normals[indexLast + 1] = normals[indexFirst + 1];
  60643. normals[indexLast + 2] = normals[indexFirst + 2];
  60644. }
  60645. }
  60646. if (!(instance.areNormalsFrozen)) {
  60647. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60648. }
  60649. }
  60650. return instance;
  60651. }
  60652. else { // new ribbon creation
  60653. var ribbon = new BABYLON.Mesh(name, scene);
  60654. ribbon._originalBuilderSideOrientation = sideOrientation;
  60655. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60656. if (closePath) {
  60657. ribbon._idx = vertexData._idx;
  60658. }
  60659. ribbon._closePath = closePath;
  60660. ribbon._closeArray = closeArray;
  60661. vertexData.applyToMesh(ribbon, updatable);
  60662. return ribbon;
  60663. }
  60664. };
  60665. /**
  60666. * Creates a cylinder or a cone mesh
  60667. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60668. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60669. * * 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.
  60670. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60671. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60672. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60673. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60674. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60675. * * 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).
  60676. * * 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
  60677. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60678. * * 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
  60679. * * 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.
  60680. * * If `enclose` is false, a ring surface is one element.
  60681. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60682. * * 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
  60683. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60684. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60685. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60686. * @param name defines the name of the mesh
  60687. * @param options defines the options used to create the mesh
  60688. * @param scene defines the hosting scene
  60689. * @returns the cylinder mesh
  60690. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60691. */
  60692. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60693. var cylinder = new BABYLON.Mesh(name, scene);
  60694. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60695. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60696. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60697. vertexData.applyToMesh(cylinder, options.updatable);
  60698. return cylinder;
  60699. };
  60700. /**
  60701. * Creates a torus mesh
  60702. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60703. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60704. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60705. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60706. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60707. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60708. * @param name defines the name of the mesh
  60709. * @param options defines the options used to create the mesh
  60710. * @param scene defines the hosting scene
  60711. * @returns the torus mesh
  60712. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60713. */
  60714. MeshBuilder.CreateTorus = function (name, options, scene) {
  60715. var torus = new BABYLON.Mesh(name, scene);
  60716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60717. torus._originalBuilderSideOrientation = options.sideOrientation;
  60718. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60719. vertexData.applyToMesh(torus, options.updatable);
  60720. return torus;
  60721. };
  60722. /**
  60723. * Creates a torus knot mesh
  60724. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60725. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60726. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60727. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60728. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60729. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60730. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60731. * @param name defines the name of the mesh
  60732. * @param options defines the options used to create the mesh
  60733. * @param scene defines the hosting scene
  60734. * @returns the torus knot mesh
  60735. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60736. */
  60737. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60738. var torusKnot = new BABYLON.Mesh(name, scene);
  60739. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60740. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60741. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60742. vertexData.applyToMesh(torusKnot, options.updatable);
  60743. return torusKnot;
  60744. };
  60745. /**
  60746. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60747. * * 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
  60748. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60749. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60750. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60751. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60752. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60753. * * 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
  60754. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60755. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60756. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60757. * @param name defines the name of the new line system
  60758. * @param options defines the options used to create the line system
  60759. * @param scene defines the hosting scene
  60760. * @returns a new line system mesh
  60761. */
  60762. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60763. var instance = options.instance;
  60764. var lines = options.lines;
  60765. var colors = options.colors;
  60766. if (instance) { // lines update
  60767. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60768. var vertexColor;
  60769. var lineColors;
  60770. if (colors) {
  60771. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60772. }
  60773. var i = 0;
  60774. var c = 0;
  60775. for (var l = 0; l < lines.length; l++) {
  60776. var points = lines[l];
  60777. for (var p = 0; p < points.length; p++) {
  60778. positions[i] = points[p].x;
  60779. positions[i + 1] = points[p].y;
  60780. positions[i + 2] = points[p].z;
  60781. if (colors && vertexColor) {
  60782. lineColors = colors[l];
  60783. vertexColor[c] = lineColors[p].r;
  60784. vertexColor[c + 1] = lineColors[p].g;
  60785. vertexColor[c + 2] = lineColors[p].b;
  60786. vertexColor[c + 3] = lineColors[p].a;
  60787. c += 4;
  60788. }
  60789. i += 3;
  60790. }
  60791. }
  60792. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60793. if (colors && vertexColor) {
  60794. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60795. }
  60796. return instance;
  60797. }
  60798. // line system creation
  60799. var useVertexColor = (colors) ? true : false;
  60800. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60801. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60802. vertexData.applyToMesh(lineSystem, options.updatable);
  60803. return lineSystem;
  60804. };
  60805. /**
  60806. * Creates a line mesh
  60807. * 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
  60808. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60809. * * The parameter `points` is an array successive Vector3
  60810. * * 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
  60811. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60812. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60813. * * When updating an instance, remember that only point positions can change, not the number of points
  60814. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60815. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60816. * @param name defines the name of the new line system
  60817. * @param options defines the options used to create the line system
  60818. * @param scene defines the hosting scene
  60819. * @returns a new line mesh
  60820. */
  60821. MeshBuilder.CreateLines = function (name, options, scene) {
  60822. if (scene === void 0) { scene = null; }
  60823. var colors = (options.colors) ? [options.colors] : null;
  60824. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60825. return lines;
  60826. };
  60827. /**
  60828. * Creates a dashed line mesh
  60829. * * 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
  60830. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60831. * * The parameter `points` is an array successive Vector3
  60832. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60833. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60834. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60835. * * 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
  60836. * * When updating an instance, remember that only point positions can change, not the number of points
  60837. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60838. * @param name defines the name of the mesh
  60839. * @param options defines the options used to create the mesh
  60840. * @param scene defines the hosting scene
  60841. * @returns the dashed line mesh
  60842. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60843. */
  60844. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60845. if (scene === void 0) { scene = null; }
  60846. var points = options.points;
  60847. var instance = options.instance;
  60848. var gapSize = options.gapSize || 1;
  60849. var dashSize = options.dashSize || 3;
  60850. if (instance) { // dashed lines update
  60851. var positionFunction = function (positions) {
  60852. var curvect = BABYLON.Vector3.Zero();
  60853. var nbSeg = positions.length / 6;
  60854. var lg = 0;
  60855. var nb = 0;
  60856. var shft = 0;
  60857. var dashshft = 0;
  60858. var curshft = 0;
  60859. var p = 0;
  60860. var i = 0;
  60861. var j = 0;
  60862. for (i = 0; i < points.length - 1; i++) {
  60863. points[i + 1].subtractToRef(points[i], curvect);
  60864. lg += curvect.length();
  60865. }
  60866. shft = lg / nbSeg;
  60867. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60868. for (i = 0; i < points.length - 1; i++) {
  60869. points[i + 1].subtractToRef(points[i], curvect);
  60870. nb = Math.floor(curvect.length() / shft);
  60871. curvect.normalize();
  60872. j = 0;
  60873. while (j < nb && p < positions.length) {
  60874. curshft = shft * j;
  60875. positions[p] = points[i].x + curshft * curvect.x;
  60876. positions[p + 1] = points[i].y + curshft * curvect.y;
  60877. positions[p + 2] = points[i].z + curshft * curvect.z;
  60878. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60879. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60880. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60881. p += 6;
  60882. j++;
  60883. }
  60884. }
  60885. while (p < positions.length) {
  60886. positions[p] = points[i].x;
  60887. positions[p + 1] = points[i].y;
  60888. positions[p + 2] = points[i].z;
  60889. p += 3;
  60890. }
  60891. };
  60892. instance.updateMeshPositions(positionFunction, false);
  60893. return instance;
  60894. }
  60895. // dashed lines creation
  60896. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60897. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60898. vertexData.applyToMesh(dashedLines, options.updatable);
  60899. dashedLines.dashSize = dashSize;
  60900. dashedLines.gapSize = gapSize;
  60901. return dashedLines;
  60902. };
  60903. /**
  60904. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60905. * * 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 extruded along the Z axis.
  60906. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60907. * * 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.
  60908. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60909. * * 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
  60910. * * 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
  60911. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60912. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60913. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60914. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60915. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60916. * @param name defines the name of the mesh
  60917. * @param options defines the options used to create the mesh
  60918. * @param scene defines the hosting scene
  60919. * @returns the extruded shape mesh
  60920. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60921. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60922. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60923. */
  60924. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60925. if (scene === void 0) { scene = null; }
  60926. var path = options.path;
  60927. var shape = options.shape;
  60928. var scale = options.scale || 1;
  60929. var rotation = options.rotation || 0;
  60930. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60931. var updatable = options.updatable;
  60932. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60933. var instance = options.instance || null;
  60934. var invertUV = options.invertUV || false;
  60935. 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);
  60936. };
  60937. /**
  60938. * Creates an custom extruded shape mesh.
  60939. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60940. * * 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 extruded along the Z axis.
  60941. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60942. * * 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 and the distance of this point from the begining of the path
  60943. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60944. * * 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 and the distance of this point from the begining of the path
  60945. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60946. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60947. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60948. * * 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
  60949. * * 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
  60950. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60951. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60952. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60953. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60954. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60955. * @param name defines the name of the mesh
  60956. * @param options defines the options used to create the mesh
  60957. * @param scene defines the hosting scene
  60958. * @returns the custom extruded shape mesh
  60959. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60960. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60961. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60962. */
  60963. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60964. var path = options.path;
  60965. var shape = options.shape;
  60966. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60967. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60968. var ribbonCloseArray = options.ribbonCloseArray || false;
  60969. var ribbonClosePath = options.ribbonClosePath || false;
  60970. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60971. var updatable = options.updatable;
  60972. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60973. var instance = options.instance;
  60974. var invertUV = options.invertUV || false;
  60975. 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);
  60976. };
  60977. /**
  60978. * Creates lathe mesh.
  60979. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60980. * * 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  60981. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60982. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60983. * * 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
  60984. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60985. * * 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
  60986. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60987. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60988. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60989. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60990. * @param name defines the name of the mesh
  60991. * @param options defines the options used to create the mesh
  60992. * @param scene defines the hosting scene
  60993. * @returns the lathe mesh
  60994. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60995. */
  60996. MeshBuilder.CreateLathe = function (name, options, scene) {
  60997. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60998. var closed = (options.closed === undefined) ? true : options.closed;
  60999. var shape = options.shape;
  61000. var radius = options.radius || 1;
  61001. var tessellation = options.tessellation || 64;
  61002. var updatable = options.updatable;
  61003. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61004. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61005. var pi2 = Math.PI * 2;
  61006. var paths = new Array();
  61007. var invertUV = options.invertUV || false;
  61008. var i = 0;
  61009. var p = 0;
  61010. var step = pi2 / tessellation * arc;
  61011. var rotated;
  61012. var path = new Array();
  61013. for (i = 0; i <= tessellation; i++) {
  61014. var path = [];
  61015. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61016. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61017. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61018. }
  61019. for (p = 0; p < shape.length; p++) {
  61020. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61021. path.push(rotated);
  61022. }
  61023. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61024. 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));
  61025. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61026. }
  61027. paths.push(path);
  61028. }
  61029. // lathe ribbon
  61030. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61031. return lathe;
  61032. };
  61033. /**
  61034. * Creates a plane mesh
  61035. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61036. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61037. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61038. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61039. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61040. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61041. * @param name defines the name of the mesh
  61042. * @param options defines the options used to create the mesh
  61043. * @param scene defines the hosting scene
  61044. * @returns the plane mesh
  61045. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61046. */
  61047. MeshBuilder.CreatePlane = function (name, options, scene) {
  61048. var plane = new BABYLON.Mesh(name, scene);
  61049. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61050. plane._originalBuilderSideOrientation = options.sideOrientation;
  61051. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61052. vertexData.applyToMesh(plane, options.updatable);
  61053. if (options.sourcePlane) {
  61054. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61055. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61056. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61057. plane.rotate(vectorProduct, product);
  61058. }
  61059. return plane;
  61060. };
  61061. /**
  61062. * Creates a ground mesh
  61063. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61064. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61065. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61066. * @param name defines the name of the mesh
  61067. * @param options defines the options used to create the mesh
  61068. * @param scene defines the hosting scene
  61069. * @returns the ground mesh
  61070. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61071. */
  61072. MeshBuilder.CreateGround = function (name, options, scene) {
  61073. var ground = new BABYLON.GroundMesh(name, scene);
  61074. ground._setReady(false);
  61075. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61076. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61077. ground._width = options.width || 1;
  61078. ground._height = options.height || 1;
  61079. ground._maxX = ground._width / 2;
  61080. ground._maxZ = ground._height / 2;
  61081. ground._minX = -ground._maxX;
  61082. ground._minZ = -ground._maxZ;
  61083. var vertexData = BABYLON.VertexData.CreateGround(options);
  61084. vertexData.applyToMesh(ground, options.updatable);
  61085. ground._setReady(true);
  61086. return ground;
  61087. };
  61088. /**
  61089. * Creates a tiled ground mesh
  61090. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61091. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61092. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61093. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61094. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61095. * @param name defines the name of the mesh
  61096. * @param options defines the options used to create the mesh
  61097. * @param scene defines the hosting scene
  61098. * @returns the tiled ground mesh
  61099. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61100. */
  61101. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61102. var tiledGround = new BABYLON.Mesh(name, scene);
  61103. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61104. vertexData.applyToMesh(tiledGround, options.updatable);
  61105. return tiledGround;
  61106. };
  61107. /**
  61108. * Creates a ground mesh from a height map
  61109. * * The parameter `url` sets the URL of the height map image resource.
  61110. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61111. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61112. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61113. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61114. * * 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.
  61115. * * 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).
  61116. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61117. * @param name defines the name of the mesh
  61118. * @param url defines the url to the height map
  61119. * @param options defines the options used to create the mesh
  61120. * @param scene defines the hosting scene
  61121. * @returns the ground mesh
  61122. * @see http://doc.babylonjs.com/babylon101/height_map
  61123. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61124. */
  61125. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61126. var width = options.width || 10.0;
  61127. var height = options.height || 10.0;
  61128. var subdivisions = options.subdivisions || 1 | 0;
  61129. var minHeight = options.minHeight || 0.0;
  61130. var maxHeight = options.maxHeight || 1.0;
  61131. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61132. var updatable = options.updatable;
  61133. var onReady = options.onReady;
  61134. var ground = new BABYLON.GroundMesh(name, scene);
  61135. ground._subdivisionsX = subdivisions;
  61136. ground._subdivisionsY = subdivisions;
  61137. ground._width = width;
  61138. ground._height = height;
  61139. ground._maxX = ground._width / 2.0;
  61140. ground._maxZ = ground._height / 2.0;
  61141. ground._minX = -ground._maxX;
  61142. ground._minZ = -ground._maxZ;
  61143. ground._setReady(false);
  61144. var onload = function (img) {
  61145. // Getting height map data
  61146. var canvas = document.createElement("canvas");
  61147. var context = canvas.getContext("2d");
  61148. if (!context) {
  61149. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61150. }
  61151. if (scene.isDisposed) {
  61152. return;
  61153. }
  61154. var bufferWidth = img.width;
  61155. var bufferHeight = img.height;
  61156. canvas.width = bufferWidth;
  61157. canvas.height = bufferHeight;
  61158. context.drawImage(img, 0, 0);
  61159. // Create VertexData from map data
  61160. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61161. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61162. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61163. width: width, height: height,
  61164. subdivisions: subdivisions,
  61165. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61166. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61167. });
  61168. vertexData.applyToMesh(ground, updatable);
  61169. //execute ready callback, if set
  61170. if (onReady) {
  61171. onReady(ground);
  61172. }
  61173. ground._setReady(true);
  61174. };
  61175. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61176. return ground;
  61177. };
  61178. /**
  61179. * Creates a polygon mesh
  61180. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61181. * * 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
  61182. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61183. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61184. * * 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)
  61185. * * Remember you can only change the shape positions, not their number when updating a polygon
  61186. * @param name defines the name of the mesh
  61187. * @param options defines the options used to create the mesh
  61188. * @param scene defines the hosting scene
  61189. * @returns the polygon mesh
  61190. */
  61191. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61192. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61193. var shape = options.shape;
  61194. var holes = options.holes || [];
  61195. var depth = options.depth || 0;
  61196. var contours = [];
  61197. var hole = [];
  61198. for (var i = 0; i < shape.length; i++) {
  61199. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61200. }
  61201. var epsilon = 0.00000001;
  61202. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61203. contours.pop();
  61204. }
  61205. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61206. for (var hNb = 0; hNb < holes.length; hNb++) {
  61207. hole = [];
  61208. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61209. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61210. }
  61211. polygonTriangulation.addHole(hole);
  61212. }
  61213. var polygon = polygonTriangulation.build(options.updatable, depth);
  61214. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61215. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61216. vertexData.applyToMesh(polygon, options.updatable);
  61217. return polygon;
  61218. };
  61219. ;
  61220. /**
  61221. * Creates an extruded polygon mesh, with depth in the Y direction.
  61222. * * 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)
  61223. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61224. * @param name defines the name of the mesh
  61225. * @param options defines the options used to create the mesh
  61226. * @param scene defines the hosting scene
  61227. * @returns the polygon mesh
  61228. */
  61229. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61230. return MeshBuilder.CreatePolygon(name, options, scene);
  61231. };
  61232. ;
  61233. /**
  61234. * Creates a tube mesh.
  61235. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61236. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61237. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61238. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61239. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61240. * * 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. It must return a radius value (positive float)
  61241. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61242. * * 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
  61243. * * 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
  61244. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61245. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61246. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61247. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61248. * @param name defines the name of the mesh
  61249. * @param options defines the options used to create the mesh
  61250. * @param scene defines the hosting scene
  61251. * @returns the tube mesh
  61252. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61253. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61254. */
  61255. MeshBuilder.CreateTube = function (name, options, scene) {
  61256. var path = options.path;
  61257. var instance = options.instance;
  61258. var radius = 1.0;
  61259. if (instance) {
  61260. radius = instance.radius;
  61261. }
  61262. if (options.radius !== undefined) {
  61263. radius = options.radius;
  61264. }
  61265. ;
  61266. var tessellation = options.tessellation || 64 | 0;
  61267. var radiusFunction = options.radiusFunction || null;
  61268. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61269. var invertUV = options.invertUV || false;
  61270. var updatable = options.updatable;
  61271. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61272. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61273. // tube geometry
  61274. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61275. var tangents = path3D.getTangents();
  61276. var normals = path3D.getNormals();
  61277. var distances = path3D.getDistances();
  61278. var pi2 = Math.PI * 2;
  61279. var step = pi2 / tessellation * arc;
  61280. var returnRadius = function () { return radius; };
  61281. var radiusFunctionFinal = radiusFunction || returnRadius;
  61282. var circlePath;
  61283. var rad;
  61284. var normal;
  61285. var rotated;
  61286. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61287. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61288. for (var i = 0; i < path.length; i++) {
  61289. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61290. circlePath = Array(); // current circle array
  61291. normal = normals[i]; // current normal
  61292. for (var t = 0; t < tessellation; t++) {
  61293. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61294. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61295. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61296. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61297. circlePath[t] = rotated;
  61298. }
  61299. circlePaths[index] = circlePath;
  61300. index++;
  61301. }
  61302. // cap
  61303. var capPath = function (nbPoints, pathIndex) {
  61304. var pointCap = Array();
  61305. for (var i = 0; i < nbPoints; i++) {
  61306. pointCap.push(path[pathIndex]);
  61307. }
  61308. return pointCap;
  61309. };
  61310. switch (cap) {
  61311. case BABYLON.Mesh.NO_CAP:
  61312. break;
  61313. case BABYLON.Mesh.CAP_START:
  61314. circlePaths[0] = capPath(tessellation, 0);
  61315. circlePaths[1] = circlePaths[2].slice(0);
  61316. break;
  61317. case BABYLON.Mesh.CAP_END:
  61318. circlePaths[index] = circlePaths[index - 1].slice(0);
  61319. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61320. break;
  61321. case BABYLON.Mesh.CAP_ALL:
  61322. circlePaths[0] = capPath(tessellation, 0);
  61323. circlePaths[1] = circlePaths[2].slice(0);
  61324. circlePaths[index] = circlePaths[index - 1].slice(0);
  61325. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61326. break;
  61327. default:
  61328. break;
  61329. }
  61330. return circlePaths;
  61331. };
  61332. var path3D;
  61333. var pathArray;
  61334. if (instance) { // tube update
  61335. var arc = options.arc || instance.arc;
  61336. path3D = (instance.path3D).update(path);
  61337. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61338. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61339. instance.path3D = path3D;
  61340. instance.pathArray = pathArray;
  61341. instance.arc = arc;
  61342. instance.radius = radius;
  61343. return instance;
  61344. }
  61345. // tube creation
  61346. path3D = new BABYLON.Path3D(path);
  61347. var newPathArray = new Array();
  61348. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61349. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61350. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61351. tube.pathArray = pathArray;
  61352. tube.path3D = path3D;
  61353. tube.tessellation = tessellation;
  61354. tube.cap = cap;
  61355. tube.arc = options.arc;
  61356. tube.radius = radius;
  61357. return tube;
  61358. };
  61359. /**
  61360. * Creates a polyhedron mesh
  61361. * * 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 to choose the wanted type
  61362. * * The parameter `size` (positive float, default 1) sets the polygon size
  61363. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61364. * * 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`
  61365. * * 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
  61366. * * 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)`)
  61367. * * 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
  61368. * * 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
  61369. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61370. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61371. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61372. * @param name defines the name of the mesh
  61373. * @param options defines the options used to create the mesh
  61374. * @param scene defines the hosting scene
  61375. * @returns the polyhedron mesh
  61376. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61377. */
  61378. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61379. var polyhedron = new BABYLON.Mesh(name, scene);
  61380. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61381. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61382. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61383. vertexData.applyToMesh(polyhedron, options.updatable);
  61384. return polyhedron;
  61385. };
  61386. /**
  61387. * Creates a decal mesh.
  61388. * 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
  61389. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61390. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61391. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61392. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61393. * @param name defines the name of the mesh
  61394. * @param sourceMesh defines the mesh where the decal must be applied
  61395. * @param options defines the options used to create the mesh
  61396. * @param scene defines the hosting scene
  61397. * @returns the decal mesh
  61398. * @see http://doc.babylonjs.com/how_to/decals
  61399. */
  61400. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61401. var indices = sourceMesh.getIndices();
  61402. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61403. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61404. var position = options.position || BABYLON.Vector3.Zero();
  61405. var normal = options.normal || BABYLON.Vector3.Up();
  61406. var size = options.size || BABYLON.Vector3.One();
  61407. var angle = options.angle || 0;
  61408. // Getting correct rotation
  61409. if (!normal) {
  61410. var target = new BABYLON.Vector3(0, 0, 1);
  61411. var camera = sourceMesh.getScene().activeCamera;
  61412. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61413. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61414. }
  61415. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61416. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61417. var pitch = Math.atan2(normal.y, len);
  61418. // Matrix
  61419. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61420. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61421. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61422. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61423. var vertexData = new BABYLON.VertexData();
  61424. vertexData.indices = [];
  61425. vertexData.positions = [];
  61426. vertexData.normals = [];
  61427. vertexData.uvs = [];
  61428. var currentVertexDataIndex = 0;
  61429. var extractDecalVector3 = function (indexId) {
  61430. var result = new BABYLON.PositionNormalVertex();
  61431. if (!indices || !positions || !normals) {
  61432. return result;
  61433. }
  61434. var vertexId = indices[indexId];
  61435. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61436. // Send vector to decal local world
  61437. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61438. // Get normal
  61439. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61440. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61441. return result;
  61442. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61443. var clip = function (vertices, axis) {
  61444. if (vertices.length === 0) {
  61445. return vertices;
  61446. }
  61447. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61448. var clipVertices = function (v0, v1) {
  61449. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61450. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61451. };
  61452. var result = new Array();
  61453. for (var index = 0; index < vertices.length; index += 3) {
  61454. var v1Out;
  61455. var v2Out;
  61456. var v3Out;
  61457. var total = 0;
  61458. var nV1 = null;
  61459. var nV2 = null;
  61460. var nV3 = null;
  61461. var nV4 = null;
  61462. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61463. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61464. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61465. v1Out = d1 > 0;
  61466. v2Out = d2 > 0;
  61467. v3Out = d3 > 0;
  61468. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61469. switch (total) {
  61470. case 0:
  61471. result.push(vertices[index]);
  61472. result.push(vertices[index + 1]);
  61473. result.push(vertices[index + 2]);
  61474. break;
  61475. case 1:
  61476. if (v1Out) {
  61477. nV1 = vertices[index + 1];
  61478. nV2 = vertices[index + 2];
  61479. nV3 = clipVertices(vertices[index], nV1);
  61480. nV4 = clipVertices(vertices[index], nV2);
  61481. }
  61482. if (v2Out) {
  61483. nV1 = vertices[index];
  61484. nV2 = vertices[index + 2];
  61485. nV3 = clipVertices(vertices[index + 1], nV1);
  61486. nV4 = clipVertices(vertices[index + 1], nV2);
  61487. result.push(nV3);
  61488. result.push(nV2.clone());
  61489. result.push(nV1.clone());
  61490. result.push(nV2.clone());
  61491. result.push(nV3.clone());
  61492. result.push(nV4);
  61493. break;
  61494. }
  61495. if (v3Out) {
  61496. nV1 = vertices[index];
  61497. nV2 = vertices[index + 1];
  61498. nV3 = clipVertices(vertices[index + 2], nV1);
  61499. nV4 = clipVertices(vertices[index + 2], nV2);
  61500. }
  61501. if (nV1 && nV2 && nV3 && nV4) {
  61502. result.push(nV1.clone());
  61503. result.push(nV2.clone());
  61504. result.push(nV3);
  61505. result.push(nV4);
  61506. result.push(nV3.clone());
  61507. result.push(nV2.clone());
  61508. }
  61509. break;
  61510. case 2:
  61511. if (!v1Out) {
  61512. nV1 = vertices[index].clone();
  61513. nV2 = clipVertices(nV1, vertices[index + 1]);
  61514. nV3 = clipVertices(nV1, vertices[index + 2]);
  61515. result.push(nV1);
  61516. result.push(nV2);
  61517. result.push(nV3);
  61518. }
  61519. if (!v2Out) {
  61520. nV1 = vertices[index + 1].clone();
  61521. nV2 = clipVertices(nV1, vertices[index + 2]);
  61522. nV3 = clipVertices(nV1, vertices[index]);
  61523. result.push(nV1);
  61524. result.push(nV2);
  61525. result.push(nV3);
  61526. }
  61527. if (!v3Out) {
  61528. nV1 = vertices[index + 2].clone();
  61529. nV2 = clipVertices(nV1, vertices[index]);
  61530. nV3 = clipVertices(nV1, vertices[index + 1]);
  61531. result.push(nV1);
  61532. result.push(nV2);
  61533. result.push(nV3);
  61534. }
  61535. break;
  61536. case 3:
  61537. break;
  61538. }
  61539. }
  61540. return result;
  61541. };
  61542. for (var index = 0; index < indices.length; index += 3) {
  61543. var faceVertices = new Array();
  61544. faceVertices.push(extractDecalVector3(index));
  61545. faceVertices.push(extractDecalVector3(index + 1));
  61546. faceVertices.push(extractDecalVector3(index + 2));
  61547. // Clip
  61548. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61549. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61550. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61551. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61552. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61553. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61554. if (faceVertices.length === 0) {
  61555. continue;
  61556. }
  61557. // Add UVs and get back to world
  61558. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61559. var vertex = faceVertices[vIndex];
  61560. //TODO check for Int32Array | Uint32Array | Uint16Array
  61561. vertexData.indices.push(currentVertexDataIndex);
  61562. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61563. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61564. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61565. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61566. currentVertexDataIndex++;
  61567. }
  61568. }
  61569. // Return mesh
  61570. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61571. vertexData.applyToMesh(decal);
  61572. decal.position = position.clone();
  61573. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61574. return decal;
  61575. };
  61576. // Privates
  61577. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61578. // extrusion geometry
  61579. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61580. var tangents = path3D.getTangents();
  61581. var normals = path3D.getNormals();
  61582. var binormals = path3D.getBinormals();
  61583. var distances = path3D.getDistances();
  61584. var angle = 0;
  61585. var returnScale = function () { return scale !== null ? scale : 1; };
  61586. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61587. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61588. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61589. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61590. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61591. for (var i = 0; i < curve.length; i++) {
  61592. var shapePath = new Array();
  61593. var angleStep = rotate(i, distances[i]);
  61594. var scaleRatio = scl(i, distances[i]);
  61595. for (var p = 0; p < shape.length; p++) {
  61596. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61597. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61598. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61599. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61600. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61601. shapePath[p] = rotated;
  61602. }
  61603. shapePaths[index] = shapePath;
  61604. angle += angleStep;
  61605. index++;
  61606. }
  61607. // cap
  61608. var capPath = function (shapePath) {
  61609. var pointCap = Array();
  61610. var barycenter = BABYLON.Vector3.Zero();
  61611. var i;
  61612. for (i = 0; i < shapePath.length; i++) {
  61613. barycenter.addInPlace(shapePath[i]);
  61614. }
  61615. barycenter.scaleInPlace(1.0 / shapePath.length);
  61616. for (i = 0; i < shapePath.length; i++) {
  61617. pointCap.push(barycenter);
  61618. }
  61619. return pointCap;
  61620. };
  61621. switch (cap) {
  61622. case BABYLON.Mesh.NO_CAP:
  61623. break;
  61624. case BABYLON.Mesh.CAP_START:
  61625. shapePaths[0] = capPath(shapePaths[2]);
  61626. shapePaths[1] = shapePaths[2];
  61627. break;
  61628. case BABYLON.Mesh.CAP_END:
  61629. shapePaths[index] = shapePaths[index - 1];
  61630. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61631. break;
  61632. case BABYLON.Mesh.CAP_ALL:
  61633. shapePaths[0] = capPath(shapePaths[2]);
  61634. shapePaths[1] = shapePaths[2];
  61635. shapePaths[index] = shapePaths[index - 1];
  61636. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61637. break;
  61638. default:
  61639. break;
  61640. }
  61641. return shapePaths;
  61642. };
  61643. var path3D;
  61644. var pathArray;
  61645. if (instance) { // instance update
  61646. path3D = (instance.path3D).update(curve);
  61647. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61648. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61649. return instance;
  61650. }
  61651. // extruded shape creation
  61652. path3D = new BABYLON.Path3D(curve);
  61653. var newShapePaths = new Array();
  61654. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61655. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61656. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61657. extrudedGeneric.pathArray = pathArray;
  61658. extrudedGeneric.path3D = path3D;
  61659. extrudedGeneric.cap = cap;
  61660. return extrudedGeneric;
  61661. };
  61662. return MeshBuilder;
  61663. }());
  61664. BABYLON.MeshBuilder = MeshBuilder;
  61665. })(BABYLON || (BABYLON = {}));
  61666. //# sourceMappingURL=babylon.meshBuilder.js.map
  61667. var BABYLON;
  61668. (function (BABYLON) {
  61669. /**
  61670. * Draco compression (https://google.github.io/draco/)
  61671. */
  61672. var DracoCompression = /** @class */ (function () {
  61673. /**
  61674. * Constructor
  61675. */
  61676. function DracoCompression() {
  61677. }
  61678. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61679. /**
  61680. * Returns true if the decoder is available.
  61681. */
  61682. get: function () {
  61683. if (typeof DracoDecoderModule !== "undefined") {
  61684. return true;
  61685. }
  61686. var decoder = DracoCompression.Configuration.decoder;
  61687. if (decoder) {
  61688. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61689. return true;
  61690. }
  61691. if (decoder.fallbackUrl) {
  61692. return true;
  61693. }
  61694. }
  61695. return false;
  61696. },
  61697. enumerable: true,
  61698. configurable: true
  61699. });
  61700. /**
  61701. * Stop all async operations and release resources.
  61702. */
  61703. DracoCompression.prototype.dispose = function () {
  61704. };
  61705. /**
  61706. * Decode Draco compressed mesh data to vertex data.
  61707. * @param data The array buffer view for the Draco compression data
  61708. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61709. * @returns A promise that resolves with the decoded vertex data
  61710. */
  61711. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61712. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61713. var module = wrappedModule.module;
  61714. var vertexData = new BABYLON.VertexData();
  61715. var buffer = new module.DecoderBuffer();
  61716. buffer.Init(data, data.byteLength);
  61717. var decoder = new module.Decoder();
  61718. var geometry;
  61719. var status;
  61720. try {
  61721. var type = decoder.GetEncodedGeometryType(buffer);
  61722. switch (type) {
  61723. case module.TRIANGULAR_MESH:
  61724. geometry = new module.Mesh();
  61725. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61726. break;
  61727. case module.POINT_CLOUD:
  61728. geometry = new module.PointCloud();
  61729. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61730. break;
  61731. default:
  61732. throw new Error("Invalid geometry type " + type);
  61733. }
  61734. if (!status.ok() || !geometry.ptr) {
  61735. throw new Error(status.error_msg());
  61736. }
  61737. var numPoints = geometry.num_points();
  61738. if (type === module.TRIANGULAR_MESH) {
  61739. var numFaces = geometry.num_faces();
  61740. var faceIndices = new module.DracoInt32Array();
  61741. try {
  61742. var indices = new Uint32Array(numFaces * 3);
  61743. for (var i = 0; i < numFaces; i++) {
  61744. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61745. var offset = i * 3;
  61746. indices[offset + 0] = faceIndices.GetValue(0);
  61747. indices[offset + 1] = faceIndices.GetValue(1);
  61748. indices[offset + 2] = faceIndices.GetValue(2);
  61749. }
  61750. vertexData.indices = indices;
  61751. }
  61752. finally {
  61753. module.destroy(faceIndices);
  61754. }
  61755. }
  61756. for (var kind in attributes) {
  61757. var uniqueId = attributes[kind];
  61758. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61759. var dracoData = new module.DracoFloat32Array();
  61760. try {
  61761. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61762. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61763. for (var i = 0; i < babylonData.length; i++) {
  61764. babylonData[i] = dracoData.GetValue(i);
  61765. }
  61766. vertexData.set(babylonData, kind);
  61767. }
  61768. finally {
  61769. module.destroy(dracoData);
  61770. }
  61771. }
  61772. }
  61773. finally {
  61774. if (geometry) {
  61775. module.destroy(geometry);
  61776. }
  61777. module.destroy(decoder);
  61778. module.destroy(buffer);
  61779. }
  61780. return vertexData;
  61781. });
  61782. };
  61783. DracoCompression._GetDecoderModule = function () {
  61784. if (!DracoCompression._DecoderModulePromise) {
  61785. var promise = null;
  61786. var config_1 = {};
  61787. if (typeof DracoDecoderModule !== "undefined") {
  61788. promise = Promise.resolve();
  61789. }
  61790. else {
  61791. var decoder = DracoCompression.Configuration.decoder;
  61792. if (decoder) {
  61793. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61794. promise = Promise.all([
  61795. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61796. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61797. config_1.wasmBinary = data;
  61798. })
  61799. ]);
  61800. }
  61801. else if (decoder.fallbackUrl) {
  61802. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61803. }
  61804. }
  61805. }
  61806. if (!promise) {
  61807. throw new Error("Draco decoder module is not available");
  61808. }
  61809. DracoCompression._DecoderModulePromise = promise.then(function () {
  61810. return new Promise(function (resolve) {
  61811. config_1.onModuleLoaded = function (decoderModule) {
  61812. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61813. resolve({ module: decoderModule });
  61814. };
  61815. DracoDecoderModule(config_1);
  61816. });
  61817. });
  61818. }
  61819. return DracoCompression._DecoderModulePromise;
  61820. };
  61821. DracoCompression._LoadScriptAsync = function (url) {
  61822. return new Promise(function (resolve, reject) {
  61823. BABYLON.Tools.LoadScript(url, function () {
  61824. resolve();
  61825. }, function (message) {
  61826. reject(new Error(message));
  61827. });
  61828. });
  61829. };
  61830. DracoCompression._LoadFileAsync = function (url) {
  61831. return new Promise(function (resolve, reject) {
  61832. BABYLON.Tools.LoadFile(url, function (data) {
  61833. resolve(data);
  61834. }, undefined, undefined, true, function (request, exception) {
  61835. reject(exception);
  61836. });
  61837. });
  61838. };
  61839. /**
  61840. * The configuration.
  61841. */
  61842. DracoCompression.Configuration = {
  61843. decoder: {
  61844. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61845. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61846. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61847. }
  61848. };
  61849. return DracoCompression;
  61850. }());
  61851. BABYLON.DracoCompression = DracoCompression;
  61852. })(BABYLON || (BABYLON = {}));
  61853. //# sourceMappingURL=babylon.dracoCompression.js.map
  61854. var BABYLON;
  61855. (function (BABYLON) {
  61856. var AudioEngine = /** @class */ (function () {
  61857. function AudioEngine() {
  61858. this._audioContext = null;
  61859. this._audioContextInitialized = false;
  61860. this.canUseWebAudio = false;
  61861. this.WarnedWebAudioUnsupported = false;
  61862. this.unlocked = false;
  61863. this.isMP3supported = false;
  61864. this.isOGGsupported = false;
  61865. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61866. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61867. this.canUseWebAudio = true;
  61868. }
  61869. var audioElem = document.createElement('audio');
  61870. try {
  61871. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61872. this.isMP3supported = true;
  61873. }
  61874. }
  61875. catch (e) {
  61876. // protect error during capability check.
  61877. }
  61878. try {
  61879. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61880. this.isOGGsupported = true;
  61881. }
  61882. }
  61883. catch (e) {
  61884. // protect error during capability check.
  61885. }
  61886. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61887. this._unlockiOSaudio();
  61888. }
  61889. else {
  61890. this.unlocked = true;
  61891. }
  61892. }
  61893. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61894. get: function () {
  61895. if (!this._audioContextInitialized) {
  61896. this._initializeAudioContext();
  61897. }
  61898. return this._audioContext;
  61899. },
  61900. enumerable: true,
  61901. configurable: true
  61902. });
  61903. AudioEngine.prototype._unlockiOSaudio = function () {
  61904. var _this = this;
  61905. var unlockaudio = function () {
  61906. if (!_this.audioContext) {
  61907. return;
  61908. }
  61909. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61910. var source = _this.audioContext.createBufferSource();
  61911. source.buffer = buffer;
  61912. source.connect(_this.audioContext.destination);
  61913. source.start(0);
  61914. setTimeout(function () {
  61915. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61916. _this.unlocked = true;
  61917. window.removeEventListener('touchend', unlockaudio, false);
  61918. if (_this.onAudioUnlocked) {
  61919. _this.onAudioUnlocked();
  61920. }
  61921. }
  61922. }, 0);
  61923. };
  61924. window.addEventListener('touchend', unlockaudio, false);
  61925. };
  61926. AudioEngine.prototype._initializeAudioContext = function () {
  61927. try {
  61928. if (this.canUseWebAudio) {
  61929. this._audioContext = new AudioContext();
  61930. // create a global volume gain node
  61931. this.masterGain = this._audioContext.createGain();
  61932. this.masterGain.gain.value = 1;
  61933. this.masterGain.connect(this._audioContext.destination);
  61934. this._audioContextInitialized = true;
  61935. }
  61936. }
  61937. catch (e) {
  61938. this.canUseWebAudio = false;
  61939. BABYLON.Tools.Error("Web Audio: " + e.message);
  61940. }
  61941. };
  61942. AudioEngine.prototype.dispose = function () {
  61943. if (this.canUseWebAudio && this._audioContextInitialized) {
  61944. if (this._connectedAnalyser && this._audioContext) {
  61945. this._connectedAnalyser.stopDebugCanvas();
  61946. this._connectedAnalyser.dispose();
  61947. this.masterGain.disconnect();
  61948. this.masterGain.connect(this._audioContext.destination);
  61949. this._connectedAnalyser = null;
  61950. }
  61951. this.masterGain.gain.value = 1;
  61952. }
  61953. this.WarnedWebAudioUnsupported = false;
  61954. };
  61955. AudioEngine.prototype.getGlobalVolume = function () {
  61956. if (this.canUseWebAudio && this._audioContextInitialized) {
  61957. return this.masterGain.gain.value;
  61958. }
  61959. else {
  61960. return -1;
  61961. }
  61962. };
  61963. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61964. if (this.canUseWebAudio && this._audioContextInitialized) {
  61965. this.masterGain.gain.value = newVolume;
  61966. }
  61967. };
  61968. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61969. if (this._connectedAnalyser) {
  61970. this._connectedAnalyser.stopDebugCanvas();
  61971. }
  61972. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61973. this._connectedAnalyser = analyser;
  61974. this.masterGain.disconnect();
  61975. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61976. }
  61977. };
  61978. return AudioEngine;
  61979. }());
  61980. BABYLON.AudioEngine = AudioEngine;
  61981. })(BABYLON || (BABYLON = {}));
  61982. //# sourceMappingURL=babylon.audioEngine.js.map
  61983. var BABYLON;
  61984. (function (BABYLON) {
  61985. var Sound = /** @class */ (function () {
  61986. /**
  61987. * Create a sound and attach it to a scene
  61988. * @param name Name of your sound
  61989. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61990. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61991. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61992. */
  61993. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61994. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61995. var _this = this;
  61996. this.autoplay = false;
  61997. this.loop = false;
  61998. this.useCustomAttenuation = false;
  61999. this.spatialSound = false;
  62000. this.refDistance = 1;
  62001. this.rolloffFactor = 1;
  62002. this.maxDistance = 100;
  62003. this.distanceModel = "linear";
  62004. this._panningModel = "equalpower";
  62005. this._playbackRate = 1;
  62006. this._streaming = false;
  62007. this._startTime = 0;
  62008. this._startOffset = 0;
  62009. this._position = BABYLON.Vector3.Zero();
  62010. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62011. this._volume = 1;
  62012. this._isReadyToPlay = false;
  62013. this.isPlaying = false;
  62014. this.isPaused = false;
  62015. this._isDirectional = false;
  62016. // Used if you'd like to create a directional sound.
  62017. // If not set, the sound will be omnidirectional
  62018. this._coneInnerAngle = 360;
  62019. this._coneOuterAngle = 360;
  62020. this._coneOuterGain = 0;
  62021. this._isOutputConnected = false;
  62022. this._urlType = "Unknown";
  62023. this.name = name;
  62024. this._scene = scene;
  62025. this._readyToPlayCallback = readyToPlayCallback;
  62026. // Default custom attenuation function is a linear attenuation
  62027. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62028. if (currentDistance < maxDistance) {
  62029. return currentVolume * (1 - currentDistance / maxDistance);
  62030. }
  62031. else {
  62032. return 0;
  62033. }
  62034. };
  62035. if (options) {
  62036. this.autoplay = options.autoplay || false;
  62037. this.loop = options.loop || false;
  62038. // if volume === 0, we need another way to check this option
  62039. if (options.volume !== undefined) {
  62040. this._volume = options.volume;
  62041. }
  62042. this.spatialSound = options.spatialSound || false;
  62043. this.maxDistance = options.maxDistance || 100;
  62044. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62045. this.rolloffFactor = options.rolloffFactor || 1;
  62046. this.refDistance = options.refDistance || 1;
  62047. this.distanceModel = options.distanceModel || "linear";
  62048. this._playbackRate = options.playbackRate || 1;
  62049. this._streaming = options.streaming || false;
  62050. }
  62051. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62052. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62053. this._soundGain.gain.value = this._volume;
  62054. this._inputAudioNode = this._soundGain;
  62055. this._ouputAudioNode = this._soundGain;
  62056. if (this.spatialSound) {
  62057. this._createSpatialParameters();
  62058. }
  62059. this._scene.mainSoundTrack.AddSound(this);
  62060. var validParameter = true;
  62061. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62062. if (urlOrArrayBuffer) {
  62063. try {
  62064. if (typeof (urlOrArrayBuffer) === "string")
  62065. this._urlType = "String";
  62066. if (Array.isArray(urlOrArrayBuffer))
  62067. this._urlType = "Array";
  62068. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62069. this._urlType = "ArrayBuffer";
  62070. var urls = [];
  62071. var codecSupportedFound = false;
  62072. switch (this._urlType) {
  62073. case "ArrayBuffer":
  62074. if (urlOrArrayBuffer.byteLength > 0) {
  62075. codecSupportedFound = true;
  62076. this._soundLoaded(urlOrArrayBuffer);
  62077. }
  62078. break;
  62079. case "String":
  62080. urls.push(urlOrArrayBuffer);
  62081. case "Array":
  62082. if (urls.length === 0)
  62083. urls = urlOrArrayBuffer;
  62084. // If we found a supported format, we load it immediately and stop the loop
  62085. for (var i = 0; i < urls.length; i++) {
  62086. var url = urls[i];
  62087. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62088. codecSupportedFound = true;
  62089. }
  62090. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62091. codecSupportedFound = true;
  62092. }
  62093. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62094. codecSupportedFound = true;
  62095. }
  62096. if (url.indexOf("blob:") !== -1) {
  62097. codecSupportedFound = true;
  62098. }
  62099. if (codecSupportedFound) {
  62100. // Loading sound using XHR2
  62101. if (!this._streaming) {
  62102. this._scene._loadFile(url, function (data) {
  62103. _this._soundLoaded(data);
  62104. }, undefined, true, true, function (exception) {
  62105. if (exception) {
  62106. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62107. }
  62108. BABYLON.Tools.Error("Sound creation aborted.");
  62109. _this._scene.mainSoundTrack.RemoveSound(_this);
  62110. });
  62111. }
  62112. // Streaming sound using HTML5 Audio tag
  62113. else {
  62114. this._htmlAudioElement = new Audio(url);
  62115. this._htmlAudioElement.controls = false;
  62116. this._htmlAudioElement.loop = this.loop;
  62117. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62118. this._htmlAudioElement.preload = "auto";
  62119. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62120. _this._isReadyToPlay = true;
  62121. if (_this.autoplay) {
  62122. _this.play();
  62123. }
  62124. if (_this._readyToPlayCallback) {
  62125. _this._readyToPlayCallback();
  62126. }
  62127. });
  62128. document.body.appendChild(this._htmlAudioElement);
  62129. }
  62130. break;
  62131. }
  62132. }
  62133. break;
  62134. default:
  62135. validParameter = false;
  62136. break;
  62137. }
  62138. if (!validParameter) {
  62139. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62140. }
  62141. else {
  62142. if (!codecSupportedFound) {
  62143. this._isReadyToPlay = true;
  62144. // Simulating a ready to play event to avoid breaking code path
  62145. if (this._readyToPlayCallback) {
  62146. window.setTimeout(function () {
  62147. if (_this._readyToPlayCallback) {
  62148. _this._readyToPlayCallback();
  62149. }
  62150. }, 1000);
  62151. }
  62152. }
  62153. }
  62154. }
  62155. catch (ex) {
  62156. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62157. this._scene.mainSoundTrack.RemoveSound(this);
  62158. }
  62159. }
  62160. }
  62161. else {
  62162. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62163. this._scene.mainSoundTrack.AddSound(this);
  62164. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62165. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62166. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62167. }
  62168. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62169. if (this._readyToPlayCallback) {
  62170. window.setTimeout(function () {
  62171. if (_this._readyToPlayCallback) {
  62172. _this._readyToPlayCallback();
  62173. }
  62174. }, 1000);
  62175. }
  62176. }
  62177. }
  62178. Sound.prototype.dispose = function () {
  62179. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62180. if (this.isPlaying) {
  62181. this.stop();
  62182. }
  62183. this._isReadyToPlay = false;
  62184. if (this.soundTrackId === -1) {
  62185. this._scene.mainSoundTrack.RemoveSound(this);
  62186. }
  62187. else {
  62188. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62189. }
  62190. if (this._soundGain) {
  62191. this._soundGain.disconnect();
  62192. this._soundGain = null;
  62193. }
  62194. if (this._soundPanner) {
  62195. this._soundPanner.disconnect();
  62196. this._soundPanner = null;
  62197. }
  62198. if (this._soundSource) {
  62199. this._soundSource.disconnect();
  62200. this._soundSource = null;
  62201. }
  62202. this._audioBuffer = null;
  62203. if (this._htmlAudioElement) {
  62204. this._htmlAudioElement.pause();
  62205. this._htmlAudioElement.src = "";
  62206. document.body.removeChild(this._htmlAudioElement);
  62207. }
  62208. if (this._connectedMesh && this._registerFunc) {
  62209. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62210. this._connectedMesh = null;
  62211. }
  62212. }
  62213. };
  62214. Sound.prototype.isReady = function () {
  62215. return this._isReadyToPlay;
  62216. };
  62217. Sound.prototype._soundLoaded = function (audioData) {
  62218. var _this = this;
  62219. if (!BABYLON.Engine.audioEngine.audioContext) {
  62220. return;
  62221. }
  62222. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62223. _this._audioBuffer = buffer;
  62224. _this._isReadyToPlay = true;
  62225. if (_this.autoplay) {
  62226. _this.play();
  62227. }
  62228. if (_this._readyToPlayCallback) {
  62229. _this._readyToPlayCallback();
  62230. }
  62231. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62232. };
  62233. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62234. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62235. this._audioBuffer = audioBuffer;
  62236. this._isReadyToPlay = true;
  62237. }
  62238. };
  62239. Sound.prototype.updateOptions = function (options) {
  62240. if (options) {
  62241. this.loop = options.loop || this.loop;
  62242. this.maxDistance = options.maxDistance || this.maxDistance;
  62243. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62244. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62245. this.refDistance = options.refDistance || this.refDistance;
  62246. this.distanceModel = options.distanceModel || this.distanceModel;
  62247. this._playbackRate = options.playbackRate || this._playbackRate;
  62248. this._updateSpatialParameters();
  62249. if (this.isPlaying) {
  62250. if (this._streaming) {
  62251. this._htmlAudioElement.playbackRate = this._playbackRate;
  62252. }
  62253. else {
  62254. if (this._soundSource) {
  62255. this._soundSource.playbackRate.value = this._playbackRate;
  62256. }
  62257. }
  62258. }
  62259. }
  62260. };
  62261. Sound.prototype._createSpatialParameters = function () {
  62262. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62263. if (this._scene.headphone) {
  62264. this._panningModel = "HRTF";
  62265. }
  62266. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62267. this._updateSpatialParameters();
  62268. this._soundPanner.connect(this._ouputAudioNode);
  62269. this._inputAudioNode = this._soundPanner;
  62270. }
  62271. };
  62272. Sound.prototype._updateSpatialParameters = function () {
  62273. if (this.spatialSound && this._soundPanner) {
  62274. if (this.useCustomAttenuation) {
  62275. // Tricks to disable in a way embedded Web Audio attenuation
  62276. this._soundPanner.distanceModel = "linear";
  62277. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62278. this._soundPanner.refDistance = 1;
  62279. this._soundPanner.rolloffFactor = 1;
  62280. this._soundPanner.panningModel = this._panningModel;
  62281. }
  62282. else {
  62283. this._soundPanner.distanceModel = this.distanceModel;
  62284. this._soundPanner.maxDistance = this.maxDistance;
  62285. this._soundPanner.refDistance = this.refDistance;
  62286. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62287. this._soundPanner.panningModel = this._panningModel;
  62288. }
  62289. }
  62290. };
  62291. Sound.prototype.switchPanningModelToHRTF = function () {
  62292. this._panningModel = "HRTF";
  62293. this._switchPanningModel();
  62294. };
  62295. Sound.prototype.switchPanningModelToEqualPower = function () {
  62296. this._panningModel = "equalpower";
  62297. this._switchPanningModel();
  62298. };
  62299. Sound.prototype._switchPanningModel = function () {
  62300. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62301. this._soundPanner.panningModel = this._panningModel;
  62302. }
  62303. };
  62304. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62305. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62306. if (this._isOutputConnected) {
  62307. this._ouputAudioNode.disconnect();
  62308. }
  62309. this._ouputAudioNode.connect(soundTrackAudioNode);
  62310. this._isOutputConnected = true;
  62311. }
  62312. };
  62313. /**
  62314. * Transform this sound into a directional source
  62315. * @param coneInnerAngle Size of the inner cone in degree
  62316. * @param coneOuterAngle Size of the outer cone in degree
  62317. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62318. */
  62319. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62320. if (coneOuterAngle < coneInnerAngle) {
  62321. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62322. return;
  62323. }
  62324. this._coneInnerAngle = coneInnerAngle;
  62325. this._coneOuterAngle = coneOuterAngle;
  62326. this._coneOuterGain = coneOuterGain;
  62327. this._isDirectional = true;
  62328. if (this.isPlaying && this.loop) {
  62329. this.stop();
  62330. this.play();
  62331. }
  62332. };
  62333. Sound.prototype.setPosition = function (newPosition) {
  62334. this._position = newPosition;
  62335. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62336. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62337. }
  62338. };
  62339. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62340. this._localDirection = newLocalDirection;
  62341. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62342. this._updateDirection();
  62343. }
  62344. };
  62345. Sound.prototype._updateDirection = function () {
  62346. if (!this._connectedMesh || !this._soundPanner) {
  62347. return;
  62348. }
  62349. var mat = this._connectedMesh.getWorldMatrix();
  62350. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62351. direction.normalize();
  62352. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62353. };
  62354. Sound.prototype.updateDistanceFromListener = function () {
  62355. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62356. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62357. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62358. }
  62359. };
  62360. Sound.prototype.setAttenuationFunction = function (callback) {
  62361. this._customAttenuationFunction = callback;
  62362. };
  62363. /**
  62364. * Play the sound
  62365. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62366. * @param offset (optional) Start the sound setting it at a specific time
  62367. */
  62368. Sound.prototype.play = function (time, offset) {
  62369. var _this = this;
  62370. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62371. try {
  62372. if (this._startOffset < 0) {
  62373. time = -this._startOffset;
  62374. this._startOffset = 0;
  62375. }
  62376. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62377. if (!this._soundSource || !this._streamingSource) {
  62378. if (this.spatialSound && this._soundPanner) {
  62379. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62380. if (this._isDirectional) {
  62381. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62382. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62383. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62384. if (this._connectedMesh) {
  62385. this._updateDirection();
  62386. }
  62387. else {
  62388. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62389. }
  62390. }
  62391. }
  62392. }
  62393. if (this._streaming) {
  62394. if (!this._streamingSource) {
  62395. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62396. this._htmlAudioElement.onended = function () { _this._onended(); };
  62397. this._htmlAudioElement.playbackRate = this._playbackRate;
  62398. }
  62399. this._streamingSource.disconnect();
  62400. this._streamingSource.connect(this._inputAudioNode);
  62401. this._htmlAudioElement.play();
  62402. }
  62403. else {
  62404. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62405. this._soundSource.buffer = this._audioBuffer;
  62406. this._soundSource.connect(this._inputAudioNode);
  62407. this._soundSource.loop = this.loop;
  62408. this._soundSource.playbackRate.value = this._playbackRate;
  62409. this._soundSource.onended = function () { _this._onended(); };
  62410. if (this._soundSource.buffer) {
  62411. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62412. }
  62413. }
  62414. this._startTime = startTime;
  62415. this.isPlaying = true;
  62416. this.isPaused = false;
  62417. }
  62418. catch (ex) {
  62419. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62420. }
  62421. }
  62422. };
  62423. Sound.prototype._onended = function () {
  62424. this.isPlaying = false;
  62425. if (this.onended) {
  62426. this.onended();
  62427. }
  62428. };
  62429. /**
  62430. * Stop the sound
  62431. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62432. */
  62433. Sound.prototype.stop = function (time) {
  62434. if (this.isPlaying) {
  62435. if (this._streaming) {
  62436. this._htmlAudioElement.pause();
  62437. // Test needed for Firefox or it will generate an Invalid State Error
  62438. if (this._htmlAudioElement.currentTime > 0) {
  62439. this._htmlAudioElement.currentTime = 0;
  62440. }
  62441. }
  62442. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62443. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62444. this._soundSource.stop(stopTime);
  62445. this._soundSource.onended = function () { };
  62446. if (!this.isPaused) {
  62447. this._startOffset = 0;
  62448. }
  62449. }
  62450. this.isPlaying = false;
  62451. }
  62452. };
  62453. Sound.prototype.pause = function () {
  62454. if (this.isPlaying) {
  62455. this.isPaused = true;
  62456. if (this._streaming) {
  62457. this._htmlAudioElement.pause();
  62458. }
  62459. else if (BABYLON.Engine.audioEngine.audioContext) {
  62460. this.stop(0);
  62461. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62462. }
  62463. }
  62464. };
  62465. Sound.prototype.setVolume = function (newVolume, time) {
  62466. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62467. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62468. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62469. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62470. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62471. }
  62472. else {
  62473. this._soundGain.gain.value = newVolume;
  62474. }
  62475. }
  62476. this._volume = newVolume;
  62477. };
  62478. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62479. this._playbackRate = newPlaybackRate;
  62480. if (this.isPlaying) {
  62481. if (this._streaming) {
  62482. this._htmlAudioElement.playbackRate = this._playbackRate;
  62483. }
  62484. else if (this._soundSource) {
  62485. this._soundSource.playbackRate.value = this._playbackRate;
  62486. }
  62487. }
  62488. };
  62489. Sound.prototype.getVolume = function () {
  62490. return this._volume;
  62491. };
  62492. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62493. var _this = this;
  62494. if (this._connectedMesh && this._registerFunc) {
  62495. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62496. this._registerFunc = null;
  62497. }
  62498. this._connectedMesh = meshToConnectTo;
  62499. if (!this.spatialSound) {
  62500. this.spatialSound = true;
  62501. this._createSpatialParameters();
  62502. if (this.isPlaying && this.loop) {
  62503. this.stop();
  62504. this.play();
  62505. }
  62506. }
  62507. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62508. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62509. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62510. };
  62511. Sound.prototype.detachFromMesh = function () {
  62512. if (this._connectedMesh && this._registerFunc) {
  62513. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62514. this._registerFunc = null;
  62515. this._connectedMesh = null;
  62516. }
  62517. };
  62518. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62519. if (!node.getBoundingInfo) {
  62520. return;
  62521. }
  62522. var mesh = node;
  62523. var boundingInfo = mesh.getBoundingInfo();
  62524. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62525. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62526. this._updateDirection();
  62527. }
  62528. };
  62529. Sound.prototype.clone = function () {
  62530. var _this = this;
  62531. if (!this._streaming) {
  62532. var setBufferAndRun = function () {
  62533. if (_this._isReadyToPlay) {
  62534. clonedSound._audioBuffer = _this.getAudioBuffer();
  62535. clonedSound._isReadyToPlay = true;
  62536. if (clonedSound.autoplay) {
  62537. clonedSound.play();
  62538. }
  62539. }
  62540. else {
  62541. window.setTimeout(setBufferAndRun, 300);
  62542. }
  62543. };
  62544. var currentOptions = {
  62545. autoplay: this.autoplay, loop: this.loop,
  62546. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62547. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62548. refDistance: this.refDistance, distanceModel: this.distanceModel
  62549. };
  62550. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62551. if (this.useCustomAttenuation) {
  62552. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62553. }
  62554. clonedSound.setPosition(this._position);
  62555. clonedSound.setPlaybackRate(this._playbackRate);
  62556. setBufferAndRun();
  62557. return clonedSound;
  62558. }
  62559. // Can't clone a streaming sound
  62560. else {
  62561. return null;
  62562. }
  62563. };
  62564. Sound.prototype.getAudioBuffer = function () {
  62565. return this._audioBuffer;
  62566. };
  62567. Sound.prototype.serialize = function () {
  62568. var serializationObject = {
  62569. name: this.name,
  62570. url: this.name,
  62571. autoplay: this.autoplay,
  62572. loop: this.loop,
  62573. volume: this._volume,
  62574. spatialSound: this.spatialSound,
  62575. maxDistance: this.maxDistance,
  62576. rolloffFactor: this.rolloffFactor,
  62577. refDistance: this.refDistance,
  62578. distanceModel: this.distanceModel,
  62579. playbackRate: this._playbackRate,
  62580. panningModel: this._panningModel,
  62581. soundTrackId: this.soundTrackId
  62582. };
  62583. if (this.spatialSound) {
  62584. if (this._connectedMesh)
  62585. serializationObject.connectedMeshId = this._connectedMesh.id;
  62586. serializationObject.position = this._position.asArray();
  62587. serializationObject.refDistance = this.refDistance;
  62588. serializationObject.distanceModel = this.distanceModel;
  62589. serializationObject.isDirectional = this._isDirectional;
  62590. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62591. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62592. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62593. serializationObject.coneOuterGain = this._coneOuterGain;
  62594. }
  62595. return serializationObject;
  62596. };
  62597. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62598. var soundName = parsedSound.name;
  62599. var soundUrl;
  62600. if (parsedSound.url) {
  62601. soundUrl = rootUrl + parsedSound.url;
  62602. }
  62603. else {
  62604. soundUrl = rootUrl + soundName;
  62605. }
  62606. var options = {
  62607. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62608. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62609. rolloffFactor: parsedSound.rolloffFactor,
  62610. refDistance: parsedSound.refDistance,
  62611. distanceModel: parsedSound.distanceModel,
  62612. playbackRate: parsedSound.playbackRate
  62613. };
  62614. var newSound;
  62615. if (!sourceSound) {
  62616. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62617. scene._addPendingData(newSound);
  62618. }
  62619. else {
  62620. var setBufferAndRun = function () {
  62621. if (sourceSound._isReadyToPlay) {
  62622. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62623. newSound._isReadyToPlay = true;
  62624. if (newSound.autoplay) {
  62625. newSound.play();
  62626. }
  62627. }
  62628. else {
  62629. window.setTimeout(setBufferAndRun, 300);
  62630. }
  62631. };
  62632. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62633. setBufferAndRun();
  62634. }
  62635. if (parsedSound.position) {
  62636. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62637. newSound.setPosition(soundPosition);
  62638. }
  62639. if (parsedSound.isDirectional) {
  62640. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62641. if (parsedSound.localDirectionToMesh) {
  62642. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62643. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62644. }
  62645. }
  62646. if (parsedSound.connectedMeshId) {
  62647. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62648. if (connectedMesh) {
  62649. newSound.attachToMesh(connectedMesh);
  62650. }
  62651. }
  62652. return newSound;
  62653. };
  62654. return Sound;
  62655. }());
  62656. BABYLON.Sound = Sound;
  62657. })(BABYLON || (BABYLON = {}));
  62658. //# sourceMappingURL=babylon.sound.js.map
  62659. var BABYLON;
  62660. (function (BABYLON) {
  62661. var SoundTrack = /** @class */ (function () {
  62662. function SoundTrack(scene, options) {
  62663. this.id = -1;
  62664. this._isMainTrack = false;
  62665. this._isInitialized = false;
  62666. this._scene = scene;
  62667. this.soundCollection = new Array();
  62668. this._options = options;
  62669. if (!this._isMainTrack) {
  62670. this._scene.soundTracks.push(this);
  62671. this.id = this._scene.soundTracks.length - 1;
  62672. }
  62673. }
  62674. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62675. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62676. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62677. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62678. if (this._options) {
  62679. if (this._options.volume) {
  62680. this._outputAudioNode.gain.value = this._options.volume;
  62681. }
  62682. if (this._options.mainTrack) {
  62683. this._isMainTrack = this._options.mainTrack;
  62684. }
  62685. }
  62686. this._isInitialized = true;
  62687. }
  62688. };
  62689. SoundTrack.prototype.dispose = function () {
  62690. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62691. if (this._connectedAnalyser) {
  62692. this._connectedAnalyser.stopDebugCanvas();
  62693. }
  62694. while (this.soundCollection.length) {
  62695. this.soundCollection[0].dispose();
  62696. }
  62697. if (this._outputAudioNode) {
  62698. this._outputAudioNode.disconnect();
  62699. }
  62700. this._outputAudioNode = null;
  62701. }
  62702. };
  62703. SoundTrack.prototype.AddSound = function (sound) {
  62704. if (!this._isInitialized) {
  62705. this._initializeSoundTrackAudioGraph();
  62706. }
  62707. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62708. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62709. }
  62710. if (sound.soundTrackId) {
  62711. if (sound.soundTrackId === -1) {
  62712. this._scene.mainSoundTrack.RemoveSound(sound);
  62713. }
  62714. else {
  62715. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62716. }
  62717. }
  62718. this.soundCollection.push(sound);
  62719. sound.soundTrackId = this.id;
  62720. };
  62721. SoundTrack.prototype.RemoveSound = function (sound) {
  62722. var index = this.soundCollection.indexOf(sound);
  62723. if (index !== -1) {
  62724. this.soundCollection.splice(index, 1);
  62725. }
  62726. };
  62727. SoundTrack.prototype.setVolume = function (newVolume) {
  62728. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62729. this._outputAudioNode.gain.value = newVolume;
  62730. }
  62731. };
  62732. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62733. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62734. for (var i = 0; i < this.soundCollection.length; i++) {
  62735. this.soundCollection[i].switchPanningModelToHRTF();
  62736. }
  62737. }
  62738. };
  62739. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62740. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62741. for (var i = 0; i < this.soundCollection.length; i++) {
  62742. this.soundCollection[i].switchPanningModelToEqualPower();
  62743. }
  62744. }
  62745. };
  62746. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62747. if (this._connectedAnalyser) {
  62748. this._connectedAnalyser.stopDebugCanvas();
  62749. }
  62750. this._connectedAnalyser = analyser;
  62751. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62752. this._outputAudioNode.disconnect();
  62753. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62754. }
  62755. };
  62756. return SoundTrack;
  62757. }());
  62758. BABYLON.SoundTrack = SoundTrack;
  62759. })(BABYLON || (BABYLON = {}));
  62760. //# sourceMappingURL=babylon.soundtrack.js.map
  62761. var BABYLON;
  62762. (function (BABYLON) {
  62763. /**
  62764. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62765. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62766. */
  62767. var Analyser = /** @class */ (function () {
  62768. /**
  62769. * Creates a new analyser
  62770. * @param scene defines hosting scene
  62771. */
  62772. function Analyser(scene) {
  62773. /**
  62774. * Gets or sets the smoothing
  62775. * @ignorenaming
  62776. */
  62777. this.SMOOTHING = 0.75;
  62778. /**
  62779. * Gets or sets the FFT table size
  62780. * @ignorenaming
  62781. */
  62782. this.FFT_SIZE = 512;
  62783. /**
  62784. * Gets or sets the bar graph amplitude
  62785. * @ignorenaming
  62786. */
  62787. this.BARGRAPHAMPLITUDE = 256;
  62788. /**
  62789. * Gets or sets the position of the debug canvas
  62790. * @ignorenaming
  62791. */
  62792. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62793. /**
  62794. * Gets or sets the debug canvas size
  62795. * @ignorenaming
  62796. */
  62797. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62798. this._scene = scene;
  62799. this._audioEngine = BABYLON.Engine.audioEngine;
  62800. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62801. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62802. this._webAudioAnalyser.minDecibels = -140;
  62803. this._webAudioAnalyser.maxDecibels = 0;
  62804. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62805. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62806. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62807. }
  62808. }
  62809. /**
  62810. * Get the number of data values you will have to play with for the visualization
  62811. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62812. * @returns a number
  62813. */
  62814. Analyser.prototype.getFrequencyBinCount = function () {
  62815. if (this._audioEngine.canUseWebAudio) {
  62816. return this._webAudioAnalyser.frequencyBinCount;
  62817. }
  62818. else {
  62819. return 0;
  62820. }
  62821. };
  62822. /**
  62823. * Gets the current frequency data as a byte array
  62824. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62825. * @returns a Uint8Array
  62826. */
  62827. Analyser.prototype.getByteFrequencyData = function () {
  62828. if (this._audioEngine.canUseWebAudio) {
  62829. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62830. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62831. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62832. }
  62833. return this._byteFreqs;
  62834. };
  62835. /**
  62836. * Gets the current waveform as a byte array
  62837. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62838. * @returns a Uint8Array
  62839. */
  62840. Analyser.prototype.getByteTimeDomainData = function () {
  62841. if (this._audioEngine.canUseWebAudio) {
  62842. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62843. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62844. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62845. }
  62846. return this._byteTime;
  62847. };
  62848. /**
  62849. * Gets the current frequency data as a float array
  62850. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62851. * @returns a Float32Array
  62852. */
  62853. Analyser.prototype.getFloatFrequencyData = function () {
  62854. if (this._audioEngine.canUseWebAudio) {
  62855. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62856. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62857. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62858. }
  62859. return this._floatFreqs;
  62860. };
  62861. /**
  62862. * Renders the debug canvas
  62863. */
  62864. Analyser.prototype.drawDebugCanvas = function () {
  62865. var _this = this;
  62866. if (this._audioEngine.canUseWebAudio) {
  62867. if (!this._debugCanvas) {
  62868. this._debugCanvas = document.createElement("canvas");
  62869. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62870. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62871. this._debugCanvas.style.position = "absolute";
  62872. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62873. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62874. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62875. document.body.appendChild(this._debugCanvas);
  62876. this._registerFunc = function () {
  62877. _this.drawDebugCanvas();
  62878. };
  62879. this._scene.registerBeforeRender(this._registerFunc);
  62880. }
  62881. if (this._registerFunc && this._debugCanvasContext) {
  62882. var workingArray = this.getByteFrequencyData();
  62883. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62884. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62885. // Draw the frequency domain chart.
  62886. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62887. var value = workingArray[i];
  62888. var percent = value / this.BARGRAPHAMPLITUDE;
  62889. var height = this.DEBUGCANVASSIZE.height * percent;
  62890. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62891. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62892. var hue = i / this.getFrequencyBinCount() * 360;
  62893. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62894. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62895. }
  62896. }
  62897. }
  62898. };
  62899. /**
  62900. * Stops rendering the debug canvas and removes it
  62901. */
  62902. Analyser.prototype.stopDebugCanvas = function () {
  62903. if (this._debugCanvas) {
  62904. if (this._registerFunc) {
  62905. this._scene.unregisterBeforeRender(this._registerFunc);
  62906. this._registerFunc = null;
  62907. }
  62908. document.body.removeChild(this._debugCanvas);
  62909. this._debugCanvas = null;
  62910. this._debugCanvasContext = null;
  62911. }
  62912. };
  62913. /**
  62914. * Connects two audio nodes
  62915. * @param inputAudioNode defines first node to connect
  62916. * @param outputAudioNode defines second node to connect
  62917. */
  62918. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62919. if (this._audioEngine.canUseWebAudio) {
  62920. inputAudioNode.connect(this._webAudioAnalyser);
  62921. this._webAudioAnalyser.connect(outputAudioNode);
  62922. }
  62923. };
  62924. /**
  62925. * Releases all associated resources
  62926. */
  62927. Analyser.prototype.dispose = function () {
  62928. if (this._audioEngine.canUseWebAudio) {
  62929. this._webAudioAnalyser.disconnect();
  62930. }
  62931. };
  62932. return Analyser;
  62933. }());
  62934. BABYLON.Analyser = Analyser;
  62935. })(BABYLON || (BABYLON = {}));
  62936. //# sourceMappingURL=babylon.analyser.js.map
  62937. var BABYLON;
  62938. (function (BABYLON) {
  62939. var CubeTexture = /** @class */ (function (_super) {
  62940. __extends(CubeTexture, _super);
  62941. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62942. if (extensions === void 0) { extensions = null; }
  62943. if (noMipmap === void 0) { noMipmap = false; }
  62944. if (files === void 0) { files = null; }
  62945. if (onLoad === void 0) { onLoad = null; }
  62946. if (onError === void 0) { onError = null; }
  62947. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62948. if (prefiltered === void 0) { prefiltered = false; }
  62949. if (forcedExtension === void 0) { forcedExtension = null; }
  62950. var _this = _super.call(this, scene) || this;
  62951. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62952. /**
  62953. * Gets or sets the center of the bounding box associated with the cube texture
  62954. * It must define where the camera used to render the texture was set
  62955. */
  62956. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62957. _this._rotationY = 0;
  62958. _this.name = rootUrl;
  62959. _this.url = rootUrl;
  62960. _this._noMipmap = noMipmap;
  62961. _this.hasAlpha = false;
  62962. _this._format = format;
  62963. _this._prefiltered = prefiltered;
  62964. _this.isCube = true;
  62965. _this._textureMatrix = BABYLON.Matrix.Identity();
  62966. if (prefiltered) {
  62967. _this.gammaSpace = false;
  62968. }
  62969. if (!rootUrl && !files) {
  62970. return _this;
  62971. }
  62972. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62973. var lastDot = rootUrl.lastIndexOf(".");
  62974. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62975. var isDDS = (extension === ".dds");
  62976. if (!files) {
  62977. if (!isDDS && !extensions) {
  62978. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62979. }
  62980. files = [];
  62981. if (extensions) {
  62982. for (var index = 0; index < extensions.length; index++) {
  62983. files.push(rootUrl + extensions[index]);
  62984. }
  62985. }
  62986. }
  62987. _this._files = files;
  62988. if (!_this._texture) {
  62989. if (!scene.useDelayedTextureLoading) {
  62990. if (prefiltered) {
  62991. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62992. }
  62993. else {
  62994. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62995. }
  62996. }
  62997. else {
  62998. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62999. }
  63000. }
  63001. else if (onLoad) {
  63002. if (_this._texture.isReady) {
  63003. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63004. }
  63005. else {
  63006. _this._texture.onLoadedObservable.add(onLoad);
  63007. }
  63008. }
  63009. return _this;
  63010. }
  63011. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63012. get: function () {
  63013. return this._boundingBoxSize;
  63014. },
  63015. /**
  63016. * Gets or sets the size of the bounding box associated with the cube texture
  63017. * When defined, the cubemap will switch to local mode
  63018. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63019. * @example https://www.babylonjs-playground.com/#RNASML
  63020. */
  63021. set: function (value) {
  63022. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63023. return;
  63024. }
  63025. this._boundingBoxSize = value;
  63026. var scene = this.getScene();
  63027. if (scene) {
  63028. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63029. }
  63030. },
  63031. enumerable: true,
  63032. configurable: true
  63033. });
  63034. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63035. /**
  63036. * Gets texture matrix rotation angle around Y axis radians.
  63037. */
  63038. get: function () {
  63039. return this._rotationY;
  63040. },
  63041. /**
  63042. * Sets texture matrix rotation angle around Y axis in radians.
  63043. */
  63044. set: function (value) {
  63045. this._rotationY = value;
  63046. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63047. },
  63048. enumerable: true,
  63049. configurable: true
  63050. });
  63051. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63052. var rootUrlKey = "";
  63053. files.forEach(function (url) { return rootUrlKey += url; });
  63054. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63055. };
  63056. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63057. if (forcedExtension === void 0) { forcedExtension = null; }
  63058. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63059. };
  63060. // Methods
  63061. CubeTexture.prototype.delayLoad = function () {
  63062. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63063. return;
  63064. }
  63065. var scene = this.getScene();
  63066. if (!scene) {
  63067. return;
  63068. }
  63069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63070. this._texture = this._getFromCache(this.url, this._noMipmap);
  63071. if (!this._texture) {
  63072. if (this._prefiltered) {
  63073. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63074. }
  63075. else {
  63076. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63077. }
  63078. }
  63079. };
  63080. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63081. return this._textureMatrix;
  63082. };
  63083. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63084. this._textureMatrix = value;
  63085. };
  63086. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63087. var texture = BABYLON.SerializationHelper.Parse(function () {
  63088. var prefiltered = false;
  63089. if (parsedTexture.prefiltered) {
  63090. prefiltered = parsedTexture.prefiltered;
  63091. }
  63092. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63093. }, parsedTexture, scene);
  63094. // Local Cubemaps
  63095. if (parsedTexture.boundingBoxPosition) {
  63096. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63097. }
  63098. if (parsedTexture.boundingBoxSize) {
  63099. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63100. }
  63101. // Animations
  63102. if (parsedTexture.animations) {
  63103. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63104. var parsedAnimation = parsedTexture.animations[animationIndex];
  63105. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63106. }
  63107. }
  63108. return texture;
  63109. };
  63110. CubeTexture.prototype.clone = function () {
  63111. var _this = this;
  63112. return BABYLON.SerializationHelper.Clone(function () {
  63113. var scene = _this.getScene();
  63114. if (!scene) {
  63115. return _this;
  63116. }
  63117. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63118. }, this);
  63119. };
  63120. __decorate([
  63121. BABYLON.serialize("rotationY")
  63122. ], CubeTexture.prototype, "_rotationY", void 0);
  63123. return CubeTexture;
  63124. }(BABYLON.BaseTexture));
  63125. BABYLON.CubeTexture = CubeTexture;
  63126. })(BABYLON || (BABYLON = {}));
  63127. //# sourceMappingURL=babylon.cubeTexture.js.map
  63128. var BABYLON;
  63129. (function (BABYLON) {
  63130. var RenderTargetTexture = /** @class */ (function (_super) {
  63131. __extends(RenderTargetTexture, _super);
  63132. /**
  63133. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63134. * or used a shadow, depth texture...
  63135. * @param name The friendly name of the texture
  63136. * @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)
  63137. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63138. * @param generateMipMaps True if mip maps need to be generated after render.
  63139. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63140. * @param type The type of the buffer in the RTT (int, half float, float...)
  63141. * @param isCube True if a cube texture needs to be created
  63142. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63143. * @param generateDepthBuffer True to generate a depth buffer
  63144. * @param generateStencilBuffer True to generate a stencil buffer
  63145. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63146. */
  63147. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63148. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63149. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63150. if (isCube === void 0) { isCube = false; }
  63151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63152. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63153. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63154. if (isMulti === void 0) { isMulti = false; }
  63155. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63156. _this.isCube = isCube;
  63157. /**
  63158. * Use this list to define the list of mesh you want to render.
  63159. */
  63160. _this.renderList = new Array();
  63161. _this.renderParticles = true;
  63162. _this.renderSprites = false;
  63163. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63164. _this.ignoreCameraViewport = false;
  63165. // Events
  63166. /**
  63167. * An event triggered when the texture is unbind.
  63168. */
  63169. _this.onBeforeBindObservable = new BABYLON.Observable();
  63170. /**
  63171. * An event triggered when the texture is unbind.
  63172. */
  63173. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63174. /**
  63175. * An event triggered before rendering the texture
  63176. */
  63177. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63178. /**
  63179. * An event triggered after rendering the texture
  63180. */
  63181. _this.onAfterRenderObservable = new BABYLON.Observable();
  63182. /**
  63183. * An event triggered after the texture clear
  63184. */
  63185. _this.onClearObservable = new BABYLON.Observable();
  63186. _this._currentRefreshId = -1;
  63187. _this._refreshRate = 1;
  63188. _this._samples = 1;
  63189. /**
  63190. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63191. * It must define where the camera used to render the texture is set
  63192. */
  63193. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63194. scene = _this.getScene();
  63195. if (!scene) {
  63196. return _this;
  63197. }
  63198. _this._engine = scene.getEngine();
  63199. _this.name = name;
  63200. _this.isRenderTarget = true;
  63201. _this._initialSizeParameter = size;
  63202. _this._processSizeParameter(size);
  63203. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63204. });
  63205. _this._generateMipMaps = generateMipMaps ? true : false;
  63206. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63207. // Rendering groups
  63208. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63209. if (isMulti) {
  63210. return _this;
  63211. }
  63212. _this._renderTargetOptions = {
  63213. generateMipMaps: generateMipMaps,
  63214. type: type,
  63215. samplingMode: samplingMode,
  63216. generateDepthBuffer: generateDepthBuffer,
  63217. generateStencilBuffer: generateStencilBuffer
  63218. };
  63219. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63220. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63221. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63222. }
  63223. if (isCube) {
  63224. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63225. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63226. _this._textureMatrix = BABYLON.Matrix.Identity();
  63227. }
  63228. else {
  63229. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63230. }
  63231. return _this;
  63232. }
  63233. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63234. get: function () {
  63235. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63236. },
  63237. enumerable: true,
  63238. configurable: true
  63239. });
  63240. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63241. get: function () {
  63242. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63243. },
  63244. enumerable: true,
  63245. configurable: true
  63246. });
  63247. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63248. get: function () {
  63249. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63250. },
  63251. enumerable: true,
  63252. configurable: true
  63253. });
  63254. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63255. set: function (callback) {
  63256. if (this._onAfterUnbindObserver) {
  63257. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63258. }
  63259. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63260. },
  63261. enumerable: true,
  63262. configurable: true
  63263. });
  63264. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63265. set: function (callback) {
  63266. if (this._onBeforeRenderObserver) {
  63267. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63268. }
  63269. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63270. },
  63271. enumerable: true,
  63272. configurable: true
  63273. });
  63274. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63275. set: function (callback) {
  63276. if (this._onAfterRenderObserver) {
  63277. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63278. }
  63279. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63280. },
  63281. enumerable: true,
  63282. configurable: true
  63283. });
  63284. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63285. set: function (callback) {
  63286. if (this._onClearObserver) {
  63287. this.onClearObservable.remove(this._onClearObserver);
  63288. }
  63289. this._onClearObserver = this.onClearObservable.add(callback);
  63290. },
  63291. enumerable: true,
  63292. configurable: true
  63293. });
  63294. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63295. get: function () {
  63296. return this._renderTargetOptions;
  63297. },
  63298. enumerable: true,
  63299. configurable: true
  63300. });
  63301. RenderTargetTexture.prototype._onRatioRescale = function () {
  63302. if (this._sizeRatio) {
  63303. this.resize(this._initialSizeParameter);
  63304. }
  63305. };
  63306. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63307. get: function () {
  63308. return this._boundingBoxSize;
  63309. },
  63310. /**
  63311. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63312. * When defined, the cubemap will switch to local mode
  63313. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63314. * @example https://www.babylonjs-playground.com/#RNASML
  63315. */
  63316. set: function (value) {
  63317. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63318. return;
  63319. }
  63320. this._boundingBoxSize = value;
  63321. var scene = this.getScene();
  63322. if (scene) {
  63323. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63324. }
  63325. },
  63326. enumerable: true,
  63327. configurable: true
  63328. });
  63329. /**
  63330. * Creates a depth stencil texture.
  63331. * This is only available in WebGL 2 or with the depth texture extension available.
  63332. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63333. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63334. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63335. */
  63336. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63337. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63338. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63339. if (generateStencil === void 0) { generateStencil = false; }
  63340. if (!this.getScene()) {
  63341. return;
  63342. }
  63343. var engine = this.getScene().getEngine();
  63344. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63345. bilinearFiltering: bilinearFiltering,
  63346. comparisonFunction: comparisonFunction,
  63347. generateStencil: generateStencil,
  63348. isCube: this.isCube
  63349. });
  63350. engine.setFrameBufferDepthStencilTexture(this);
  63351. };
  63352. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63353. if (size.ratio) {
  63354. this._sizeRatio = size.ratio;
  63355. this._size = {
  63356. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63357. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63358. };
  63359. }
  63360. else {
  63361. this._size = size;
  63362. }
  63363. };
  63364. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63365. get: function () {
  63366. return this._samples;
  63367. },
  63368. set: function (value) {
  63369. if (this._samples === value) {
  63370. return;
  63371. }
  63372. var scene = this.getScene();
  63373. if (!scene) {
  63374. return;
  63375. }
  63376. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63377. },
  63378. enumerable: true,
  63379. configurable: true
  63380. });
  63381. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63382. this._currentRefreshId = -1;
  63383. };
  63384. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63385. get: function () {
  63386. return this._refreshRate;
  63387. },
  63388. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63389. set: function (value) {
  63390. this._refreshRate = value;
  63391. this.resetRefreshCounter();
  63392. },
  63393. enumerable: true,
  63394. configurable: true
  63395. });
  63396. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63397. if (!this._postProcessManager) {
  63398. var scene = this.getScene();
  63399. if (!scene) {
  63400. return;
  63401. }
  63402. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63403. this._postProcesses = new Array();
  63404. }
  63405. this._postProcesses.push(postProcess);
  63406. this._postProcesses[0].autoClear = false;
  63407. };
  63408. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63409. if (!this._postProcesses) {
  63410. return;
  63411. }
  63412. if (dispose) {
  63413. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63414. var postProcess = _a[_i];
  63415. postProcess.dispose();
  63416. }
  63417. }
  63418. this._postProcesses = [];
  63419. };
  63420. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63421. if (!this._postProcesses) {
  63422. return;
  63423. }
  63424. var index = this._postProcesses.indexOf(postProcess);
  63425. if (index === -1) {
  63426. return;
  63427. }
  63428. this._postProcesses.splice(index, 1);
  63429. if (this._postProcesses.length > 0) {
  63430. this._postProcesses[0].autoClear = false;
  63431. }
  63432. };
  63433. RenderTargetTexture.prototype._shouldRender = function () {
  63434. if (this._currentRefreshId === -1) { // At least render once
  63435. this._currentRefreshId = 1;
  63436. return true;
  63437. }
  63438. if (this.refreshRate === this._currentRefreshId) {
  63439. this._currentRefreshId = 1;
  63440. return true;
  63441. }
  63442. this._currentRefreshId++;
  63443. return false;
  63444. };
  63445. RenderTargetTexture.prototype.getRenderSize = function () {
  63446. if (this._size.width) {
  63447. return this._size.width;
  63448. }
  63449. return this._size;
  63450. };
  63451. RenderTargetTexture.prototype.getRenderWidth = function () {
  63452. if (this._size.width) {
  63453. return this._size.width;
  63454. }
  63455. return this._size;
  63456. };
  63457. RenderTargetTexture.prototype.getRenderHeight = function () {
  63458. if (this._size.width) {
  63459. return this._size.height;
  63460. }
  63461. return this._size;
  63462. };
  63463. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63464. get: function () {
  63465. return true;
  63466. },
  63467. enumerable: true,
  63468. configurable: true
  63469. });
  63470. RenderTargetTexture.prototype.scale = function (ratio) {
  63471. var newSize = this.getRenderSize() * ratio;
  63472. this.resize(newSize);
  63473. };
  63474. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63475. if (this.isCube) {
  63476. return this._textureMatrix;
  63477. }
  63478. return _super.prototype.getReflectionTextureMatrix.call(this);
  63479. };
  63480. RenderTargetTexture.prototype.resize = function (size) {
  63481. this.releaseInternalTexture();
  63482. var scene = this.getScene();
  63483. if (!scene) {
  63484. return;
  63485. }
  63486. this._processSizeParameter(size);
  63487. if (this.isCube) {
  63488. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63489. }
  63490. else {
  63491. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63492. }
  63493. };
  63494. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63495. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63496. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63497. var scene = this.getScene();
  63498. if (!scene) {
  63499. return;
  63500. }
  63501. var engine = scene.getEngine();
  63502. if (this.useCameraPostProcesses !== undefined) {
  63503. useCameraPostProcess = this.useCameraPostProcesses;
  63504. }
  63505. if (this._waitingRenderList) {
  63506. this.renderList = [];
  63507. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63508. var id = this._waitingRenderList[index];
  63509. var mesh_1 = scene.getMeshByID(id);
  63510. if (mesh_1) {
  63511. this.renderList.push(mesh_1);
  63512. }
  63513. }
  63514. delete this._waitingRenderList;
  63515. }
  63516. // Is predicate defined?
  63517. if (this.renderListPredicate) {
  63518. if (this.renderList) {
  63519. this.renderList.splice(0); // Clear previous renderList
  63520. }
  63521. else {
  63522. this.renderList = [];
  63523. }
  63524. var scene = this.getScene();
  63525. if (!scene) {
  63526. return;
  63527. }
  63528. var sceneMeshes = scene.meshes;
  63529. for (var index = 0; index < sceneMeshes.length; index++) {
  63530. var mesh = sceneMeshes[index];
  63531. if (this.renderListPredicate(mesh)) {
  63532. this.renderList.push(mesh);
  63533. }
  63534. }
  63535. }
  63536. this.onBeforeBindObservable.notifyObservers(this);
  63537. // Set custom projection.
  63538. // Needs to be before binding to prevent changing the aspect ratio.
  63539. var camera;
  63540. if (this.activeCamera) {
  63541. camera = this.activeCamera;
  63542. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63543. if (this.activeCamera !== scene.activeCamera) {
  63544. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63545. }
  63546. }
  63547. else {
  63548. camera = scene.activeCamera;
  63549. if (camera) {
  63550. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63551. }
  63552. }
  63553. // Prepare renderingManager
  63554. this._renderingManager.reset();
  63555. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63556. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63557. var sceneRenderId = scene.getRenderId();
  63558. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63559. var mesh = currentRenderList[meshIndex];
  63560. if (mesh) {
  63561. if (!mesh.isReady(this.refreshRate === 0)) {
  63562. this.resetRefreshCounter();
  63563. continue;
  63564. }
  63565. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63566. var isMasked = void 0;
  63567. if (!this.renderList && camera) {
  63568. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63569. }
  63570. else {
  63571. isMasked = false;
  63572. }
  63573. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63574. mesh._activate(sceneRenderId);
  63575. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63576. var subMesh = mesh.subMeshes[subIndex];
  63577. scene._activeIndices.addCount(subMesh.indexCount, false);
  63578. this._renderingManager.dispatch(subMesh, mesh);
  63579. }
  63580. }
  63581. }
  63582. }
  63583. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63584. var particleSystem = scene.particleSystems[particleIndex];
  63585. var emitter = particleSystem.emitter;
  63586. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63587. continue;
  63588. }
  63589. if (currentRenderList.indexOf(emitter) >= 0) {
  63590. this._renderingManager.dispatchParticles(particleSystem);
  63591. }
  63592. }
  63593. if (this.isCube) {
  63594. for (var face = 0; face < 6; face++) {
  63595. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63596. scene.incrementRenderId();
  63597. scene.resetCachedMaterial();
  63598. }
  63599. }
  63600. else {
  63601. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63602. }
  63603. this.onAfterUnbindObservable.notifyObservers(this);
  63604. if (scene.activeCamera) {
  63605. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63606. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63607. }
  63608. engine.setViewport(scene.activeCamera.viewport);
  63609. }
  63610. scene.resetCachedMaterial();
  63611. };
  63612. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63613. var minimum = 128;
  63614. var x = renderDimension * scale;
  63615. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63616. // Ensure we don't exceed the render dimension (while staying POT)
  63617. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63618. };
  63619. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63620. var _this = this;
  63621. if (!this._texture) {
  63622. return;
  63623. }
  63624. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63625. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63626. });
  63627. };
  63628. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63629. var scene = this.getScene();
  63630. if (!scene) {
  63631. return;
  63632. }
  63633. var engine = scene.getEngine();
  63634. if (!this._texture) {
  63635. return;
  63636. }
  63637. // Bind
  63638. if (this._postProcessManager) {
  63639. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63640. }
  63641. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63642. if (this._texture) {
  63643. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63644. }
  63645. }
  63646. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63647. // Clear
  63648. if (this.onClearObservable.hasObservers()) {
  63649. this.onClearObservable.notifyObservers(engine);
  63650. }
  63651. else {
  63652. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63653. }
  63654. if (!this._doNotChangeAspectRatio) {
  63655. scene.updateTransformMatrix(true);
  63656. }
  63657. // Render
  63658. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63659. if (this._postProcessManager) {
  63660. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63661. }
  63662. else if (useCameraPostProcess) {
  63663. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63664. }
  63665. if (!this._doNotChangeAspectRatio) {
  63666. scene.updateTransformMatrix(true);
  63667. }
  63668. // Dump ?
  63669. if (dumpForDebug) {
  63670. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63671. }
  63672. // Unbind
  63673. if (!this.isCube || faceIndex === 5) {
  63674. if (this.isCube) {
  63675. if (faceIndex === 5) {
  63676. engine.generateMipMapsForCubemap(this._texture);
  63677. }
  63678. }
  63679. this.unbindFrameBuffer(engine, faceIndex);
  63680. }
  63681. else {
  63682. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63683. }
  63684. };
  63685. /**
  63686. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63687. * This allowed control for front to back rendering or reversly depending of the special needs.
  63688. *
  63689. * @param renderingGroupId The rendering group id corresponding to its index
  63690. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63691. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63692. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63693. */
  63694. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63695. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63696. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63697. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63698. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63699. };
  63700. /**
  63701. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63702. *
  63703. * @param renderingGroupId The rendering group id corresponding to its index
  63704. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63705. */
  63706. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63707. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63708. };
  63709. RenderTargetTexture.prototype.clone = function () {
  63710. var textureSize = this.getSize();
  63711. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63712. // Base texture
  63713. newTexture.hasAlpha = this.hasAlpha;
  63714. newTexture.level = this.level;
  63715. // RenderTarget Texture
  63716. newTexture.coordinatesMode = this.coordinatesMode;
  63717. if (this.renderList) {
  63718. newTexture.renderList = this.renderList.slice(0);
  63719. }
  63720. return newTexture;
  63721. };
  63722. RenderTargetTexture.prototype.serialize = function () {
  63723. if (!this.name) {
  63724. return null;
  63725. }
  63726. var serializationObject = _super.prototype.serialize.call(this);
  63727. serializationObject.renderTargetSize = this.getRenderSize();
  63728. serializationObject.renderList = [];
  63729. if (this.renderList) {
  63730. for (var index = 0; index < this.renderList.length; index++) {
  63731. serializationObject.renderList.push(this.renderList[index].id);
  63732. }
  63733. }
  63734. return serializationObject;
  63735. };
  63736. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63737. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63738. var objBuffer = this.getInternalTexture();
  63739. var scene = this.getScene();
  63740. if (objBuffer && scene) {
  63741. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63742. }
  63743. };
  63744. RenderTargetTexture.prototype.dispose = function () {
  63745. if (this._postProcessManager) {
  63746. this._postProcessManager.dispose();
  63747. this._postProcessManager = null;
  63748. }
  63749. this.clearPostProcesses(true);
  63750. if (this._resizeObserver) {
  63751. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63752. this._resizeObserver = null;
  63753. }
  63754. this.renderList = null;
  63755. // Remove from custom render targets
  63756. var scene = this.getScene();
  63757. if (!scene) {
  63758. return;
  63759. }
  63760. var index = scene.customRenderTargets.indexOf(this);
  63761. if (index >= 0) {
  63762. scene.customRenderTargets.splice(index, 1);
  63763. }
  63764. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63765. var camera = _a[_i];
  63766. index = camera.customRenderTargets.indexOf(this);
  63767. if (index >= 0) {
  63768. camera.customRenderTargets.splice(index, 1);
  63769. }
  63770. }
  63771. _super.prototype.dispose.call(this);
  63772. };
  63773. RenderTargetTexture.prototype._rebuild = function () {
  63774. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63775. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63776. }
  63777. if (this._postProcessManager) {
  63778. this._postProcessManager._rebuild();
  63779. }
  63780. };
  63781. /**
  63782. * Clear the info related to rendering groups preventing retention point in material dispose.
  63783. */
  63784. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63785. if (this._renderingManager) {
  63786. this._renderingManager.freeRenderingGroups();
  63787. }
  63788. };
  63789. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63790. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63791. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63792. return RenderTargetTexture;
  63793. }(BABYLON.Texture));
  63794. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63795. })(BABYLON || (BABYLON = {}));
  63796. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63797. var BABYLON;
  63798. (function (BABYLON) {
  63799. ;
  63800. var MultiRenderTarget = /** @class */ (function (_super) {
  63801. __extends(MultiRenderTarget, _super);
  63802. function MultiRenderTarget(name, size, count, scene, options) {
  63803. var _this = this;
  63804. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63805. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63806. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63807. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63808. _this._engine = scene.getEngine();
  63809. if (!_this.isSupported) {
  63810. _this.dispose();
  63811. return;
  63812. }
  63813. var types = [];
  63814. var samplingModes = [];
  63815. for (var i = 0; i < count; i++) {
  63816. if (options && options.types && options.types[i] !== undefined) {
  63817. types.push(options.types[i]);
  63818. }
  63819. else {
  63820. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63821. }
  63822. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63823. samplingModes.push(options.samplingModes[i]);
  63824. }
  63825. else {
  63826. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63827. }
  63828. }
  63829. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63830. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63831. _this._size = size;
  63832. _this._multiRenderTargetOptions = {
  63833. samplingModes: samplingModes,
  63834. generateMipMaps: generateMipMaps,
  63835. generateDepthBuffer: generateDepthBuffer,
  63836. generateStencilBuffer: generateStencilBuffer,
  63837. generateDepthTexture: generateDepthTexture,
  63838. types: types,
  63839. textureCount: count
  63840. };
  63841. _this._createInternalTextures();
  63842. _this._createTextures();
  63843. return _this;
  63844. }
  63845. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63846. get: function () {
  63847. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63848. },
  63849. enumerable: true,
  63850. configurable: true
  63851. });
  63852. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63853. get: function () {
  63854. return this._textures;
  63855. },
  63856. enumerable: true,
  63857. configurable: true
  63858. });
  63859. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63860. get: function () {
  63861. return this._textures[this._textures.length - 1];
  63862. },
  63863. enumerable: true,
  63864. configurable: true
  63865. });
  63866. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63867. set: function (wrap) {
  63868. if (this._textures) {
  63869. for (var i = 0; i < this._textures.length; i++) {
  63870. this._textures[i].wrapU = wrap;
  63871. }
  63872. }
  63873. },
  63874. enumerable: true,
  63875. configurable: true
  63876. });
  63877. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63878. set: function (wrap) {
  63879. if (this._textures) {
  63880. for (var i = 0; i < this._textures.length; i++) {
  63881. this._textures[i].wrapV = wrap;
  63882. }
  63883. }
  63884. },
  63885. enumerable: true,
  63886. configurable: true
  63887. });
  63888. MultiRenderTarget.prototype._rebuild = function () {
  63889. this.releaseInternalTextures();
  63890. this._createInternalTextures();
  63891. for (var i = 0; i < this._internalTextures.length; i++) {
  63892. var texture = this._textures[i];
  63893. texture._texture = this._internalTextures[i];
  63894. }
  63895. // Keeps references to frame buffer and stencil/depth buffer
  63896. this._texture = this._internalTextures[0];
  63897. };
  63898. MultiRenderTarget.prototype._createInternalTextures = function () {
  63899. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63900. };
  63901. MultiRenderTarget.prototype._createTextures = function () {
  63902. this._textures = [];
  63903. for (var i = 0; i < this._internalTextures.length; i++) {
  63904. var texture = new BABYLON.Texture(null, this.getScene());
  63905. texture._texture = this._internalTextures[i];
  63906. this._textures.push(texture);
  63907. }
  63908. // Keeps references to frame buffer and stencil/depth buffer
  63909. this._texture = this._internalTextures[0];
  63910. };
  63911. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63912. get: function () {
  63913. return this._samples;
  63914. },
  63915. set: function (value) {
  63916. if (this._samples === value) {
  63917. return;
  63918. }
  63919. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63920. },
  63921. enumerable: true,
  63922. configurable: true
  63923. });
  63924. MultiRenderTarget.prototype.resize = function (size) {
  63925. this.releaseInternalTextures();
  63926. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63927. this._createInternalTextures();
  63928. };
  63929. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63930. var _this = this;
  63931. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63932. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63933. });
  63934. };
  63935. MultiRenderTarget.prototype.dispose = function () {
  63936. this.releaseInternalTextures();
  63937. _super.prototype.dispose.call(this);
  63938. };
  63939. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63940. if (!this._internalTextures) {
  63941. return;
  63942. }
  63943. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63944. if (this._internalTextures[i] !== undefined) {
  63945. this._internalTextures[i].dispose();
  63946. this._internalTextures.splice(i, 1);
  63947. }
  63948. }
  63949. };
  63950. return MultiRenderTarget;
  63951. }(BABYLON.RenderTargetTexture));
  63952. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63953. })(BABYLON || (BABYLON = {}));
  63954. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63955. var BABYLON;
  63956. (function (BABYLON) {
  63957. var MirrorTexture = /** @class */ (function (_super) {
  63958. __extends(MirrorTexture, _super);
  63959. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63960. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63962. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63963. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63964. _this.scene = scene;
  63965. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63966. _this._transformMatrix = BABYLON.Matrix.Zero();
  63967. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63968. _this._adaptiveBlurKernel = 0;
  63969. _this._blurKernelX = 0;
  63970. _this._blurKernelY = 0;
  63971. _this._blurRatio = 1.0;
  63972. _this.ignoreCameraViewport = true;
  63973. _this._updateGammaSpace();
  63974. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63975. _this._updateGammaSpace;
  63976. });
  63977. _this.onBeforeRenderObservable.add(function () {
  63978. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63979. _this._savedViewMatrix = scene.getViewMatrix();
  63980. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63981. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63982. scene.clipPlane = _this.mirrorPlane;
  63983. scene.getEngine().cullBackFaces = false;
  63984. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63985. });
  63986. _this.onAfterRenderObservable.add(function () {
  63987. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63988. scene.getEngine().cullBackFaces = true;
  63989. scene._mirroredCameraPosition = null;
  63990. delete scene.clipPlane;
  63991. });
  63992. return _this;
  63993. }
  63994. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63995. get: function () {
  63996. return this._blurRatio;
  63997. },
  63998. set: function (value) {
  63999. if (this._blurRatio === value) {
  64000. return;
  64001. }
  64002. this._blurRatio = value;
  64003. this._preparePostProcesses();
  64004. },
  64005. enumerable: true,
  64006. configurable: true
  64007. });
  64008. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64009. set: function (value) {
  64010. this._adaptiveBlurKernel = value;
  64011. this._autoComputeBlurKernel();
  64012. },
  64013. enumerable: true,
  64014. configurable: true
  64015. });
  64016. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64017. set: function (value) {
  64018. this.blurKernelX = value;
  64019. this.blurKernelY = value;
  64020. },
  64021. enumerable: true,
  64022. configurable: true
  64023. });
  64024. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64025. get: function () {
  64026. return this._blurKernelX;
  64027. },
  64028. set: function (value) {
  64029. if (this._blurKernelX === value) {
  64030. return;
  64031. }
  64032. this._blurKernelX = value;
  64033. this._preparePostProcesses();
  64034. },
  64035. enumerable: true,
  64036. configurable: true
  64037. });
  64038. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64039. get: function () {
  64040. return this._blurKernelY;
  64041. },
  64042. set: function (value) {
  64043. if (this._blurKernelY === value) {
  64044. return;
  64045. }
  64046. this._blurKernelY = value;
  64047. this._preparePostProcesses();
  64048. },
  64049. enumerable: true,
  64050. configurable: true
  64051. });
  64052. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64053. var engine = this.getScene().getEngine();
  64054. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64055. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64056. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64057. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64058. };
  64059. MirrorTexture.prototype._onRatioRescale = function () {
  64060. if (this._sizeRatio) {
  64061. this.resize(this._initialSizeParameter);
  64062. if (!this._adaptiveBlurKernel) {
  64063. this._preparePostProcesses();
  64064. }
  64065. }
  64066. if (this._adaptiveBlurKernel) {
  64067. this._autoComputeBlurKernel();
  64068. }
  64069. };
  64070. MirrorTexture.prototype._updateGammaSpace = function () {
  64071. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64072. };
  64073. MirrorTexture.prototype._preparePostProcesses = function () {
  64074. this.clearPostProcesses(true);
  64075. if (this._blurKernelX && this._blurKernelY) {
  64076. var engine = this.getScene().getEngine();
  64077. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64078. 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);
  64079. this._blurX.autoClear = false;
  64080. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64081. this._blurX.inputTexture = this._texture;
  64082. }
  64083. else {
  64084. this._blurX.alwaysForcePOT = true;
  64085. }
  64086. 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);
  64087. this._blurY.autoClear = false;
  64088. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64089. this.addPostProcess(this._blurX);
  64090. this.addPostProcess(this._blurY);
  64091. }
  64092. else {
  64093. if (this._blurY) {
  64094. this.removePostProcess(this._blurY);
  64095. this._blurY.dispose();
  64096. this._blurY = null;
  64097. }
  64098. if (this._blurX) {
  64099. this.removePostProcess(this._blurX);
  64100. this._blurX.dispose();
  64101. this._blurX = null;
  64102. }
  64103. }
  64104. };
  64105. MirrorTexture.prototype.clone = function () {
  64106. var scene = this.getScene();
  64107. if (!scene) {
  64108. return this;
  64109. }
  64110. var textureSize = this.getSize();
  64111. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64112. // Base texture
  64113. newTexture.hasAlpha = this.hasAlpha;
  64114. newTexture.level = this.level;
  64115. // Mirror Texture
  64116. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64117. if (this.renderList) {
  64118. newTexture.renderList = this.renderList.slice(0);
  64119. }
  64120. return newTexture;
  64121. };
  64122. MirrorTexture.prototype.serialize = function () {
  64123. if (!this.name) {
  64124. return null;
  64125. }
  64126. var serializationObject = _super.prototype.serialize.call(this);
  64127. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64128. return serializationObject;
  64129. };
  64130. MirrorTexture.prototype.dispose = function () {
  64131. _super.prototype.dispose.call(this);
  64132. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64133. };
  64134. return MirrorTexture;
  64135. }(BABYLON.RenderTargetTexture));
  64136. BABYLON.MirrorTexture = MirrorTexture;
  64137. })(BABYLON || (BABYLON = {}));
  64138. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64139. var BABYLON;
  64140. (function (BABYLON) {
  64141. /**
  64142. * Creates a refraction texture used by refraction channel of the standard material.
  64143. * @param name the texture name
  64144. * @param size size of the underlying texture
  64145. * @param scene root scene
  64146. */
  64147. var RefractionTexture = /** @class */ (function (_super) {
  64148. __extends(RefractionTexture, _super);
  64149. function RefractionTexture(name, size, scene, generateMipMaps) {
  64150. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64151. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64152. _this.depth = 2.0;
  64153. _this.onBeforeRenderObservable.add(function () {
  64154. scene.clipPlane = _this.refractionPlane;
  64155. });
  64156. _this.onAfterRenderObservable.add(function () {
  64157. delete scene.clipPlane;
  64158. });
  64159. return _this;
  64160. }
  64161. RefractionTexture.prototype.clone = function () {
  64162. var scene = this.getScene();
  64163. if (!scene) {
  64164. return this;
  64165. }
  64166. var textureSize = this.getSize();
  64167. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64168. // Base texture
  64169. newTexture.hasAlpha = this.hasAlpha;
  64170. newTexture.level = this.level;
  64171. // Refraction Texture
  64172. newTexture.refractionPlane = this.refractionPlane.clone();
  64173. if (this.renderList) {
  64174. newTexture.renderList = this.renderList.slice(0);
  64175. }
  64176. newTexture.depth = this.depth;
  64177. return newTexture;
  64178. };
  64179. RefractionTexture.prototype.serialize = function () {
  64180. if (!this.name) {
  64181. return null;
  64182. }
  64183. var serializationObject = _super.prototype.serialize.call(this);
  64184. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64185. serializationObject.depth = this.depth;
  64186. return serializationObject;
  64187. };
  64188. return RefractionTexture;
  64189. }(BABYLON.RenderTargetTexture));
  64190. BABYLON.RefractionTexture = RefractionTexture;
  64191. })(BABYLON || (BABYLON = {}));
  64192. //# sourceMappingURL=babylon.refractionTexture.js.map
  64193. var BABYLON;
  64194. (function (BABYLON) {
  64195. /**
  64196. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64197. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64198. */
  64199. var DynamicTexture = /** @class */ (function (_super) {
  64200. __extends(DynamicTexture, _super);
  64201. /**
  64202. * Creates a {BABYLON.DynamicTexture}
  64203. * @param name defines the name of the texture
  64204. * @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
  64205. * @param scene defines the scene where you want the texture
  64206. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64207. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64208. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64209. */
  64210. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64211. if (scene === void 0) { scene = null; }
  64212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64213. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64214. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64215. _this.name = name;
  64216. _this._engine = _this.getScene().getEngine();
  64217. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64218. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64219. _this._generateMipMaps = generateMipMaps;
  64220. if (options.getContext) {
  64221. _this._canvas = options;
  64222. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64223. }
  64224. else {
  64225. _this._canvas = document.createElement("canvas");
  64226. if (options.width || options.width === 0) {
  64227. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64228. }
  64229. else {
  64230. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64231. }
  64232. }
  64233. var textureSize = _this.getSize();
  64234. _this._canvas.width = textureSize.width;
  64235. _this._canvas.height = textureSize.height;
  64236. _this._context = _this._canvas.getContext("2d");
  64237. return _this;
  64238. }
  64239. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64240. /**
  64241. * Gets the current state of canRescale
  64242. */
  64243. get: function () {
  64244. return true;
  64245. },
  64246. enumerable: true,
  64247. configurable: true
  64248. });
  64249. DynamicTexture.prototype._recreate = function (textureSize) {
  64250. this._canvas.width = textureSize.width;
  64251. this._canvas.height = textureSize.height;
  64252. this.releaseInternalTexture();
  64253. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64254. };
  64255. /**
  64256. * Scales the texture
  64257. * @param ratio the scale factor to apply to both width and height
  64258. */
  64259. DynamicTexture.prototype.scale = function (ratio) {
  64260. var textureSize = this.getSize();
  64261. textureSize.width *= ratio;
  64262. textureSize.height *= ratio;
  64263. this._recreate(textureSize);
  64264. };
  64265. /**
  64266. * Resizes the texture
  64267. * @param width the new width
  64268. * @param height the new height
  64269. */
  64270. DynamicTexture.prototype.scaleTo = function (width, height) {
  64271. var textureSize = this.getSize();
  64272. textureSize.width = width;
  64273. textureSize.height = height;
  64274. this._recreate(textureSize);
  64275. };
  64276. /**
  64277. * Gets the context of the canvas used by the texture
  64278. * @returns the canvas context of the dynamic texture
  64279. */
  64280. DynamicTexture.prototype.getContext = function () {
  64281. return this._context;
  64282. };
  64283. /**
  64284. * Clears the texture
  64285. */
  64286. DynamicTexture.prototype.clear = function () {
  64287. var size = this.getSize();
  64288. this._context.fillRect(0, 0, size.width, size.height);
  64289. };
  64290. /**
  64291. * Updates the texture
  64292. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64293. */
  64294. DynamicTexture.prototype.update = function (invertY) {
  64295. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64296. };
  64297. /**
  64298. * Draws text onto the texture
  64299. * @param text defines the text to be drawn
  64300. * @param x defines the placement of the text from the left
  64301. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64302. * @param font defines the font to be used with font-style, font-size, font-name
  64303. * @param color defines the color used for the text
  64304. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64305. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64306. * @param update defines whether texture is immediately update (default is true)
  64307. */
  64308. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64309. if (update === void 0) { update = true; }
  64310. var size = this.getSize();
  64311. if (clearColor) {
  64312. this._context.fillStyle = clearColor;
  64313. this._context.fillRect(0, 0, size.width, size.height);
  64314. }
  64315. this._context.font = font;
  64316. if (x === null || x === undefined) {
  64317. var textSize = this._context.measureText(text);
  64318. x = (size.width - textSize.width) / 2;
  64319. }
  64320. if (y === null || y === undefined) {
  64321. var fontSize = parseInt((font.replace(/\D/g, '')));
  64322. y = (size.height / 2) + (fontSize / 3.65);
  64323. }
  64324. this._context.fillStyle = color;
  64325. this._context.fillText(text, x, y);
  64326. if (update) {
  64327. this.update(invertY);
  64328. }
  64329. };
  64330. /**
  64331. * Clones the texture
  64332. * @returns the clone of the texture.
  64333. */
  64334. DynamicTexture.prototype.clone = function () {
  64335. var scene = this.getScene();
  64336. if (!scene) {
  64337. return this;
  64338. }
  64339. var textureSize = this.getSize();
  64340. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64341. // Base texture
  64342. newTexture.hasAlpha = this.hasAlpha;
  64343. newTexture.level = this.level;
  64344. // Dynamic Texture
  64345. newTexture.wrapU = this.wrapU;
  64346. newTexture.wrapV = this.wrapV;
  64347. return newTexture;
  64348. };
  64349. /** @hidden */
  64350. DynamicTexture.prototype._rebuild = function () {
  64351. this.update();
  64352. };
  64353. return DynamicTexture;
  64354. }(BABYLON.Texture));
  64355. BABYLON.DynamicTexture = DynamicTexture;
  64356. })(BABYLON || (BABYLON = {}));
  64357. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64358. var BABYLON;
  64359. (function (BABYLON) {
  64360. var VideoTexture = /** @class */ (function (_super) {
  64361. __extends(VideoTexture, _super);
  64362. /**
  64363. * Creates a video texture.
  64364. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64365. * @param {string | null} name optional name, will detect from video source, if not defined
  64366. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64367. * @param {BABYLON.Scene} scene is obviously the current scene.
  64368. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64369. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64370. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64371. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64372. */
  64373. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64374. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64375. if (invertY === void 0) { invertY = false; }
  64376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64377. if (settings === void 0) { settings = {
  64378. autoPlay: true,
  64379. loop: true,
  64380. autoUpdateTexture: true,
  64381. }; }
  64382. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64383. _this._stillImageCaptured = false;
  64384. _this._createInternalTexture = function () {
  64385. if (_this._texture != null) {
  64386. return;
  64387. }
  64388. if (!_this._engine.needPOTTextures ||
  64389. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64390. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64391. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64392. }
  64393. else {
  64394. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64395. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64396. _this._generateMipMaps = false;
  64397. }
  64398. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64399. if (!_this.video.autoplay) {
  64400. var oldHandler_1 = _this.video.onplaying;
  64401. _this.video.onplaying = function () {
  64402. _this.video.onplaying = oldHandler_1;
  64403. _this._texture.isReady = true;
  64404. _this._updateInternalTexture();
  64405. _this.video.pause();
  64406. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64407. _this.onLoadObservable.notifyObservers(_this);
  64408. }
  64409. };
  64410. _this.video.play();
  64411. }
  64412. else {
  64413. _this._texture.isReady = true;
  64414. _this._updateInternalTexture();
  64415. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64416. _this.onLoadObservable.notifyObservers(_this);
  64417. }
  64418. }
  64419. };
  64420. _this.reset = function () {
  64421. if (_this._texture == null) {
  64422. return;
  64423. }
  64424. _this._texture.dispose();
  64425. _this._texture = null;
  64426. };
  64427. _this._updateInternalTexture = function (e) {
  64428. if (_this._texture == null || !_this._texture.isReady) {
  64429. return;
  64430. }
  64431. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64432. return;
  64433. }
  64434. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64435. };
  64436. _this._engine = _this.getScene().getEngine();
  64437. _this._generateMipMaps = generateMipMaps;
  64438. _this._samplingMode = samplingMode;
  64439. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64440. _this.name = name || _this._getName(src);
  64441. _this.video = _this._getVideo(src);
  64442. if (settings.autoPlay !== undefined) {
  64443. _this.video.autoplay = settings.autoPlay;
  64444. }
  64445. if (settings.loop !== undefined) {
  64446. _this.video.loop = settings.loop;
  64447. }
  64448. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64449. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64450. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64451. _this.video.addEventListener("emptied", _this.reset);
  64452. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64453. _this._createInternalTexture();
  64454. }
  64455. return _this;
  64456. }
  64457. VideoTexture.prototype._getName = function (src) {
  64458. if (src instanceof HTMLVideoElement) {
  64459. return src.currentSrc;
  64460. }
  64461. if (typeof src === "object") {
  64462. return src.toString();
  64463. }
  64464. return src;
  64465. };
  64466. ;
  64467. VideoTexture.prototype._getVideo = function (src) {
  64468. if (src instanceof HTMLVideoElement) {
  64469. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64470. return src;
  64471. }
  64472. var video = document.createElement("video");
  64473. if (typeof src === "string") {
  64474. BABYLON.Tools.SetCorsBehavior(src, video);
  64475. video.src = src;
  64476. }
  64477. else {
  64478. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64479. src.forEach(function (url) {
  64480. var source = document.createElement("source");
  64481. source.src = url;
  64482. video.appendChild(source);
  64483. });
  64484. }
  64485. return video;
  64486. };
  64487. ;
  64488. /**
  64489. * Internal method to initiate `update`.
  64490. */
  64491. VideoTexture.prototype._rebuild = function () {
  64492. this.update();
  64493. };
  64494. /**
  64495. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64496. */
  64497. VideoTexture.prototype.update = function () {
  64498. if (!this.autoUpdateTexture) {
  64499. // Expecting user to call `updateTexture` manually
  64500. return;
  64501. }
  64502. this.updateTexture(true);
  64503. };
  64504. /**
  64505. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64506. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64507. */
  64508. VideoTexture.prototype.updateTexture = function (isVisible) {
  64509. if (!isVisible) {
  64510. return;
  64511. }
  64512. if (this.video.paused && this._stillImageCaptured) {
  64513. return;
  64514. }
  64515. this._stillImageCaptured = true;
  64516. this._updateInternalTexture();
  64517. };
  64518. /**
  64519. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64520. * @param url New url.
  64521. */
  64522. VideoTexture.prototype.updateURL = function (url) {
  64523. this.video.src = url;
  64524. };
  64525. VideoTexture.prototype.dispose = function () {
  64526. _super.prototype.dispose.call(this);
  64527. this.video.removeEventListener("canplay", this._createInternalTexture);
  64528. this.video.removeEventListener("paused", this._updateInternalTexture);
  64529. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64530. this.video.removeEventListener("emptied", this.reset);
  64531. this.video.pause();
  64532. };
  64533. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64534. var video = document.createElement("video");
  64535. var constraintsDeviceId;
  64536. if (constraints && constraints.deviceId) {
  64537. constraintsDeviceId = {
  64538. exact: constraints.deviceId,
  64539. };
  64540. }
  64541. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64542. if (navigator.mediaDevices) {
  64543. navigator.mediaDevices.getUserMedia({ video: constraints })
  64544. .then(function (stream) {
  64545. if (video.mozSrcObject !== undefined) {
  64546. // hack for Firefox < 19
  64547. video.mozSrcObject = stream;
  64548. }
  64549. else {
  64550. video.srcObject = stream;
  64551. }
  64552. var onPlaying = function () {
  64553. if (onReady) {
  64554. onReady(new VideoTexture("video", video, scene, true, true));
  64555. }
  64556. video.removeEventListener("playing", onPlaying);
  64557. };
  64558. video.addEventListener("playing", onPlaying);
  64559. video.play();
  64560. })
  64561. .catch(function (err) {
  64562. BABYLON.Tools.Error(err.name);
  64563. });
  64564. }
  64565. else {
  64566. navigator.getUserMedia =
  64567. navigator.getUserMedia ||
  64568. navigator.webkitGetUserMedia ||
  64569. navigator.mozGetUserMedia ||
  64570. navigator.msGetUserMedia;
  64571. if (navigator.getUserMedia) {
  64572. navigator.getUserMedia({
  64573. video: {
  64574. deviceId: constraintsDeviceId,
  64575. width: {
  64576. min: (constraints && constraints.minWidth) || 256,
  64577. max: (constraints && constraints.maxWidth) || 640,
  64578. },
  64579. height: {
  64580. min: (constraints && constraints.minHeight) || 256,
  64581. max: (constraints && constraints.maxHeight) || 480,
  64582. },
  64583. },
  64584. }, function (stream) {
  64585. if (video.mozSrcObject !== undefined) {
  64586. // hack for Firefox < 19
  64587. video.mozSrcObject = stream;
  64588. }
  64589. else {
  64590. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64591. }
  64592. video.play();
  64593. if (onReady) {
  64594. onReady(new VideoTexture("video", video, scene, true, true));
  64595. }
  64596. }, function (e) {
  64597. BABYLON.Tools.Error(e.name);
  64598. });
  64599. }
  64600. }
  64601. };
  64602. return VideoTexture;
  64603. }(BABYLON.Texture));
  64604. BABYLON.VideoTexture = VideoTexture;
  64605. })(BABYLON || (BABYLON = {}));
  64606. //# sourceMappingURL=babylon.videoTexture.js.map
  64607. var BABYLON;
  64608. (function (BABYLON) {
  64609. var RawTexture = /** @class */ (function (_super) {
  64610. __extends(RawTexture, _super);
  64611. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64612. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64613. if (invertY === void 0) { invertY = false; }
  64614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64615. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64616. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64617. _this.format = format;
  64618. _this._engine = scene.getEngine();
  64619. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64620. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64621. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64622. return _this;
  64623. }
  64624. RawTexture.prototype.update = function (data) {
  64625. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64626. };
  64627. // Statics
  64628. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64629. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64630. if (invertY === void 0) { invertY = false; }
  64631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64632. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64633. };
  64634. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64635. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64636. if (invertY === void 0) { invertY = false; }
  64637. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64638. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64639. };
  64640. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64641. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64642. if (invertY === void 0) { invertY = false; }
  64643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64644. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64645. };
  64646. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64647. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64648. if (invertY === void 0) { invertY = false; }
  64649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64650. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64651. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64652. };
  64653. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64654. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64655. if (invertY === void 0) { invertY = false; }
  64656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64657. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64658. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64659. };
  64660. return RawTexture;
  64661. }(BABYLON.Texture));
  64662. BABYLON.RawTexture = RawTexture;
  64663. })(BABYLON || (BABYLON = {}));
  64664. //# sourceMappingURL=babylon.rawTexture.js.map
  64665. var BABYLON;
  64666. (function (BABYLON) {
  64667. /**
  64668. * Class used to store 3D textures containing user data
  64669. */
  64670. var RawTexture3D = /** @class */ (function (_super) {
  64671. __extends(RawTexture3D, _super);
  64672. /**
  64673. * Create a new RawTexture3D
  64674. * @param data defines the data of the texture
  64675. * @param width defines the width of the texture
  64676. * @param height defines the height of the texture
  64677. * @param depth defines the depth of the texture
  64678. * @param format defines the texture format to use
  64679. * @param scene defines the hosting scene
  64680. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64681. * @param invertY defines if texture must be stored with Y axis inverted
  64682. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64683. */
  64684. function RawTexture3D(data, width, height, depth,
  64685. /** Gets or sets the texture format to use*/
  64686. format, scene, generateMipMaps, invertY, samplingMode) {
  64687. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64688. if (invertY === void 0) { invertY = false; }
  64689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64690. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64691. _this.format = format;
  64692. _this._engine = scene.getEngine();
  64693. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64694. _this.is3D = true;
  64695. return _this;
  64696. }
  64697. /**
  64698. * Update the texture with new data
  64699. * @param data defines the data to store in the texture
  64700. */
  64701. RawTexture3D.prototype.update = function (data) {
  64702. if (!this._texture) {
  64703. return;
  64704. }
  64705. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64706. };
  64707. return RawTexture3D;
  64708. }(BABYLON.Texture));
  64709. BABYLON.RawTexture3D = RawTexture3D;
  64710. })(BABYLON || (BABYLON = {}));
  64711. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64712. var BABYLON;
  64713. (function (BABYLON) {
  64714. /**
  64715. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64716. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64717. */
  64718. var PostProcess = /** @class */ (function () {
  64719. /**
  64720. * Creates a new instance PostProcess
  64721. * @param name The name of the PostProcess.
  64722. * @param fragmentUrl The url of the fragment shader to be used.
  64723. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64724. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64725. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64726. * @param camera The camera to apply the render pass to.
  64727. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64728. * @param engine The engine which the post process will be applied. (default: current engine)
  64729. * @param reusable If the post process can be reused on the same frame. (default: false)
  64730. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64731. * @param textureType Type of textures used when performing the post process. (default: 0)
  64732. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64733. * @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
  64734. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64735. */
  64736. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64738. if (defines === void 0) { defines = null; }
  64739. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64740. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64741. if (blockCompilation === void 0) { blockCompilation = false; }
  64742. this.name = name;
  64743. /**
  64744. * Width of the texture to apply the post process on
  64745. */
  64746. this.width = -1;
  64747. /**
  64748. * Height of the texture to apply the post process on
  64749. */
  64750. this.height = -1;
  64751. /**
  64752. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64753. */
  64754. this._outputTexture = null;
  64755. /**
  64756. * If the buffer needs to be cleared before applying the post process. (default: true)
  64757. * Should be set to false if shader will overwrite all previous pixels.
  64758. */
  64759. this.autoClear = true;
  64760. /**
  64761. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64762. */
  64763. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64764. /**
  64765. * Animations to be used for the post processing
  64766. */
  64767. this.animations = new Array();
  64768. /**
  64769. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64770. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64771. */
  64772. this.enablePixelPerfectMode = false;
  64773. /**
  64774. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64775. */
  64776. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64777. /**
  64778. * Force textures to be a power of two (default: false)
  64779. */
  64780. this.alwaysForcePOT = false;
  64781. /**
  64782. * Number of sample textures (default: 1)
  64783. */
  64784. this.samples = 1;
  64785. /**
  64786. * Modify the scale of the post process to be the same as the viewport (default: false)
  64787. */
  64788. this.adaptScaleToCurrentViewport = false;
  64789. this._reusable = false;
  64790. /**
  64791. * Smart array of input and output textures for the post process.
  64792. */
  64793. this._textures = new BABYLON.SmartArray(2);
  64794. /**
  64795. * The index in _textures that corresponds to the output texture.
  64796. */
  64797. this._currentRenderTextureInd = 0;
  64798. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64799. this._texelSize = BABYLON.Vector2.Zero();
  64800. // Events
  64801. /**
  64802. * An event triggered when the postprocess is activated.
  64803. */
  64804. this.onActivateObservable = new BABYLON.Observable();
  64805. /**
  64806. * An event triggered when the postprocess changes its size.
  64807. */
  64808. this.onSizeChangedObservable = new BABYLON.Observable();
  64809. /**
  64810. * An event triggered when the postprocess applies its effect.
  64811. */
  64812. this.onApplyObservable = new BABYLON.Observable();
  64813. /**
  64814. * An event triggered before rendering the postprocess
  64815. */
  64816. this.onBeforeRenderObservable = new BABYLON.Observable();
  64817. /**
  64818. * An event triggered after rendering the postprocess
  64819. */
  64820. this.onAfterRenderObservable = new BABYLON.Observable();
  64821. if (camera != null) {
  64822. this._camera = camera;
  64823. this._scene = camera.getScene();
  64824. camera.attachPostProcess(this);
  64825. this._engine = this._scene.getEngine();
  64826. this._scene.postProcesses.push(this);
  64827. }
  64828. else if (engine) {
  64829. this._engine = engine;
  64830. this._engine.postProcesses.push(this);
  64831. }
  64832. this._options = options;
  64833. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64834. this._reusable = reusable || false;
  64835. this._textureType = textureType;
  64836. this._samplers = samplers || [];
  64837. this._samplers.push("textureSampler");
  64838. this._fragmentUrl = fragmentUrl;
  64839. this._vertexUrl = vertexUrl;
  64840. this._parameters = parameters || [];
  64841. this._parameters.push("scale");
  64842. this._indexParameters = indexParameters;
  64843. if (!blockCompilation) {
  64844. this.updateEffect(defines);
  64845. }
  64846. }
  64847. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64848. /**
  64849. * A function that is added to the onActivateObservable
  64850. */
  64851. set: function (callback) {
  64852. if (this._onActivateObserver) {
  64853. this.onActivateObservable.remove(this._onActivateObserver);
  64854. }
  64855. if (callback) {
  64856. this._onActivateObserver = this.onActivateObservable.add(callback);
  64857. }
  64858. },
  64859. enumerable: true,
  64860. configurable: true
  64861. });
  64862. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64863. /**
  64864. * A function that is added to the onSizeChangedObservable
  64865. */
  64866. set: function (callback) {
  64867. if (this._onSizeChangedObserver) {
  64868. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64869. }
  64870. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64871. },
  64872. enumerable: true,
  64873. configurable: true
  64874. });
  64875. Object.defineProperty(PostProcess.prototype, "onApply", {
  64876. /**
  64877. * A function that is added to the onApplyObservable
  64878. */
  64879. set: function (callback) {
  64880. if (this._onApplyObserver) {
  64881. this.onApplyObservable.remove(this._onApplyObserver);
  64882. }
  64883. this._onApplyObserver = this.onApplyObservable.add(callback);
  64884. },
  64885. enumerable: true,
  64886. configurable: true
  64887. });
  64888. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64889. /**
  64890. * A function that is added to the onBeforeRenderObservable
  64891. */
  64892. set: function (callback) {
  64893. if (this._onBeforeRenderObserver) {
  64894. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64895. }
  64896. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64897. },
  64898. enumerable: true,
  64899. configurable: true
  64900. });
  64901. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64902. /**
  64903. * A function that is added to the onAfterRenderObservable
  64904. */
  64905. set: function (callback) {
  64906. if (this._onAfterRenderObserver) {
  64907. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64908. }
  64909. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64910. },
  64911. enumerable: true,
  64912. configurable: true
  64913. });
  64914. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64915. /**
  64916. * 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
  64917. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64918. */
  64919. get: function () {
  64920. return this._textures.data[this._currentRenderTextureInd];
  64921. },
  64922. set: function (value) {
  64923. this._forcedOutputTexture = value;
  64924. },
  64925. enumerable: true,
  64926. configurable: true
  64927. });
  64928. /**
  64929. * Gets the camera which post process is applied to.
  64930. * @returns The camera the post process is applied to.
  64931. */
  64932. PostProcess.prototype.getCamera = function () {
  64933. return this._camera;
  64934. };
  64935. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64936. /**
  64937. * Gets the texel size of the postprocess.
  64938. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64939. */
  64940. get: function () {
  64941. if (this._shareOutputWithPostProcess) {
  64942. return this._shareOutputWithPostProcess.texelSize;
  64943. }
  64944. if (this._forcedOutputTexture) {
  64945. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64946. }
  64947. return this._texelSize;
  64948. },
  64949. enumerable: true,
  64950. configurable: true
  64951. });
  64952. /**
  64953. * Gets the engine which this post process belongs to.
  64954. * @returns The engine the post process was enabled with.
  64955. */
  64956. PostProcess.prototype.getEngine = function () {
  64957. return this._engine;
  64958. };
  64959. /**
  64960. * The effect that is created when initializing the post process.
  64961. * @returns The created effect corrisponding the the postprocess.
  64962. */
  64963. PostProcess.prototype.getEffect = function () {
  64964. return this._effect;
  64965. };
  64966. /**
  64967. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64968. * @param postProcess The post process to share the output with.
  64969. * @returns This post process.
  64970. */
  64971. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64972. this._disposeTextures();
  64973. this._shareOutputWithPostProcess = postProcess;
  64974. return this;
  64975. };
  64976. /**
  64977. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64978. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64979. */
  64980. PostProcess.prototype.useOwnOutput = function () {
  64981. if (this._textures.length == 0) {
  64982. this._textures = new BABYLON.SmartArray(2);
  64983. }
  64984. this._shareOutputWithPostProcess = null;
  64985. };
  64986. /**
  64987. * Updates the effect with the current post process compile time values and recompiles the shader.
  64988. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64989. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64990. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64991. * @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
  64992. * @param onCompiled Called when the shader has been compiled.
  64993. * @param onError Called if there is an error when compiling a shader.
  64994. */
  64995. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64996. if (defines === void 0) { defines = null; }
  64997. if (uniforms === void 0) { uniforms = null; }
  64998. if (samplers === void 0) { samplers = null; }
  64999. 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);
  65000. };
  65001. /**
  65002. * The post process is reusable if it can be used multiple times within one frame.
  65003. * @returns If the post process is reusable
  65004. */
  65005. PostProcess.prototype.isReusable = function () {
  65006. return this._reusable;
  65007. };
  65008. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65009. PostProcess.prototype.markTextureDirty = function () {
  65010. this.width = -1;
  65011. };
  65012. /**
  65013. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65014. * 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.
  65015. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65016. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65017. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65018. * @returns The target texture that was bound to be written to.
  65019. */
  65020. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65021. var _this = this;
  65022. if (sourceTexture === void 0) { sourceTexture = null; }
  65023. camera = camera || this._camera;
  65024. var scene = camera.getScene();
  65025. var engine = scene.getEngine();
  65026. var maxSize = engine.getCaps().maxTextureSize;
  65027. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65028. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65029. // 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
  65030. var webVRCamera = camera.parent;
  65031. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65032. requiredWidth /= 2;
  65033. }
  65034. var desiredWidth = (this._options.width || requiredWidth);
  65035. var desiredHeight = this._options.height || requiredHeight;
  65036. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65037. if (this.adaptScaleToCurrentViewport) {
  65038. var currentViewport = engine.currentViewport;
  65039. if (currentViewport) {
  65040. desiredWidth *= currentViewport.width;
  65041. desiredHeight *= currentViewport.height;
  65042. }
  65043. }
  65044. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65045. if (!this._options.width) {
  65046. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65047. }
  65048. if (!this._options.height) {
  65049. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65050. }
  65051. }
  65052. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65053. if (this._textures.length > 0) {
  65054. for (var i = 0; i < this._textures.length; i++) {
  65055. this._engine._releaseTexture(this._textures.data[i]);
  65056. }
  65057. this._textures.reset();
  65058. }
  65059. this.width = desiredWidth;
  65060. this.height = desiredHeight;
  65061. var textureSize = { width: this.width, height: this.height };
  65062. var textureOptions = {
  65063. generateMipMaps: false,
  65064. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65065. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65066. samplingMode: this.renderTargetSamplingMode,
  65067. type: this._textureType
  65068. };
  65069. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65070. if (this._reusable) {
  65071. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65072. }
  65073. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65074. this.onSizeChangedObservable.notifyObservers(this);
  65075. }
  65076. this._textures.forEach(function (texture) {
  65077. if (texture.samples !== _this.samples) {
  65078. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65079. }
  65080. });
  65081. }
  65082. var target;
  65083. if (this._shareOutputWithPostProcess) {
  65084. target = this._shareOutputWithPostProcess.inputTexture;
  65085. }
  65086. else if (this._forcedOutputTexture) {
  65087. target = this._forcedOutputTexture;
  65088. this.width = this._forcedOutputTexture.width;
  65089. this.height = this._forcedOutputTexture.height;
  65090. }
  65091. else {
  65092. target = this.inputTexture;
  65093. }
  65094. // Bind the input of this post process to be used as the output of the previous post process.
  65095. if (this.enablePixelPerfectMode) {
  65096. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65097. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65098. }
  65099. else {
  65100. this._scaleRatio.copyFromFloats(1, 1);
  65101. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65102. }
  65103. this.onActivateObservable.notifyObservers(camera);
  65104. // Clear
  65105. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65106. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65107. }
  65108. if (this._reusable) {
  65109. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65110. }
  65111. return target;
  65112. };
  65113. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65114. /**
  65115. * If the post process is supported.
  65116. */
  65117. get: function () {
  65118. return this._effect.isSupported;
  65119. },
  65120. enumerable: true,
  65121. configurable: true
  65122. });
  65123. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65124. /**
  65125. * The aspect ratio of the output texture.
  65126. */
  65127. get: function () {
  65128. if (this._shareOutputWithPostProcess) {
  65129. return this._shareOutputWithPostProcess.aspectRatio;
  65130. }
  65131. if (this._forcedOutputTexture) {
  65132. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65133. }
  65134. return this.width / this.height;
  65135. },
  65136. enumerable: true,
  65137. configurable: true
  65138. });
  65139. /**
  65140. * Get a value indicating if the post-process is ready to be used
  65141. * @returns true if the post-process is ready (shader is compiled)
  65142. */
  65143. PostProcess.prototype.isReady = function () {
  65144. return this._effect && this._effect.isReady();
  65145. };
  65146. /**
  65147. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65148. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65149. */
  65150. PostProcess.prototype.apply = function () {
  65151. // Check
  65152. if (!this._effect || !this._effect.isReady())
  65153. return null;
  65154. // States
  65155. this._engine.enableEffect(this._effect);
  65156. this._engine.setState(false);
  65157. this._engine.setDepthBuffer(false);
  65158. this._engine.setDepthWrite(false);
  65159. // Alpha
  65160. this._engine.setAlphaMode(this.alphaMode);
  65161. if (this.alphaConstants) {
  65162. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65163. }
  65164. // Bind the output texture of the preivous post process as the input to this post process.
  65165. var source;
  65166. if (this._shareOutputWithPostProcess) {
  65167. source = this._shareOutputWithPostProcess.inputTexture;
  65168. }
  65169. else if (this._forcedOutputTexture) {
  65170. source = this._forcedOutputTexture;
  65171. }
  65172. else {
  65173. source = this.inputTexture;
  65174. }
  65175. this._effect._bindTexture("textureSampler", source);
  65176. // Parameters
  65177. this._effect.setVector2("scale", this._scaleRatio);
  65178. this.onApplyObservable.notifyObservers(this._effect);
  65179. return this._effect;
  65180. };
  65181. PostProcess.prototype._disposeTextures = function () {
  65182. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65183. return;
  65184. }
  65185. if (this._textures.length > 0) {
  65186. for (var i = 0; i < this._textures.length; i++) {
  65187. this._engine._releaseTexture(this._textures.data[i]);
  65188. }
  65189. }
  65190. this._textures.dispose();
  65191. };
  65192. /**
  65193. * Disposes the post process.
  65194. * @param camera The camera to dispose the post process on.
  65195. */
  65196. PostProcess.prototype.dispose = function (camera) {
  65197. camera = camera || this._camera;
  65198. this._disposeTextures();
  65199. if (this._scene) {
  65200. var index_1 = this._scene.postProcesses.indexOf(this);
  65201. if (index_1 !== -1) {
  65202. this._scene.postProcesses.splice(index_1, 1);
  65203. }
  65204. }
  65205. else {
  65206. var index_2 = this._engine.postProcesses.indexOf(this);
  65207. if (index_2 !== -1) {
  65208. this._engine.postProcesses.splice(index_2, 1);
  65209. }
  65210. }
  65211. if (!camera) {
  65212. return;
  65213. }
  65214. camera.detachPostProcess(this);
  65215. var index = camera._postProcesses.indexOf(this);
  65216. if (index === 0 && camera._postProcesses.length > 0) {
  65217. var firstPostProcess = this._camera._getFirstPostProcess();
  65218. if (firstPostProcess) {
  65219. firstPostProcess.markTextureDirty();
  65220. }
  65221. }
  65222. this.onActivateObservable.clear();
  65223. this.onAfterRenderObservable.clear();
  65224. this.onApplyObservable.clear();
  65225. this.onBeforeRenderObservable.clear();
  65226. this.onSizeChangedObservable.clear();
  65227. };
  65228. return PostProcess;
  65229. }());
  65230. BABYLON.PostProcess = PostProcess;
  65231. })(BABYLON || (BABYLON = {}));
  65232. //# sourceMappingURL=babylon.postProcess.js.map
  65233. var BABYLON;
  65234. (function (BABYLON) {
  65235. var PassPostProcess = /** @class */ (function (_super) {
  65236. __extends(PassPostProcess, _super);
  65237. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65238. if (camera === void 0) { camera = null; }
  65239. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65240. if (blockCompilation === void 0) { blockCompilation = false; }
  65241. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65242. }
  65243. return PassPostProcess;
  65244. }(BABYLON.PostProcess));
  65245. BABYLON.PassPostProcess = PassPostProcess;
  65246. })(BABYLON || (BABYLON = {}));
  65247. //# sourceMappingURL=babylon.passPostProcess.js.map
  65248. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65249. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65250. s = arguments[i];
  65251. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65252. t[p] = s[p];
  65253. }
  65254. return t;
  65255. };
  65256. var BABYLON;
  65257. (function (BABYLON) {
  65258. /**
  65259. * Default implementation IShadowGenerator.
  65260. * This is the main object responsible of generating shadows in the framework.
  65261. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65262. */
  65263. var ShadowGenerator = /** @class */ (function () {
  65264. /**
  65265. * Creates a ShadowGenerator object.
  65266. * A ShadowGenerator is the required tool to use the shadows.
  65267. * Each light casting shadows needs to use its own ShadowGenerator.
  65268. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65269. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65270. * @param light The light object generating the shadows.
  65271. * @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.
  65272. */
  65273. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65274. this._bias = 0.00005;
  65275. this._normalBias = 0;
  65276. this._blurBoxOffset = 1;
  65277. this._blurScale = 2;
  65278. this._blurKernel = 1;
  65279. this._useKernelBlur = false;
  65280. this._filter = ShadowGenerator.FILTER_NONE;
  65281. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65282. this._contactHardeningLightSizeUVRatio = 0.1;
  65283. this._darkness = 0;
  65284. this._transparencyShadow = false;
  65285. /**
  65286. * Controls the extent to which the shadows fade out at the edge of the frustum
  65287. * Used only by directionals and spots
  65288. */
  65289. this.frustumEdgeFalloff = 0;
  65290. /**
  65291. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65292. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65293. * It might on the other hand introduce peter panning.
  65294. */
  65295. this.forceBackFacesOnly = false;
  65296. this._lightDirection = BABYLON.Vector3.Zero();
  65297. this._viewMatrix = BABYLON.Matrix.Zero();
  65298. this._projectionMatrix = BABYLON.Matrix.Zero();
  65299. this._transformMatrix = BABYLON.Matrix.Zero();
  65300. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65301. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65302. this._currentFaceIndex = 0;
  65303. this._currentFaceIndexCache = 0;
  65304. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65305. this._mapSize = mapSize;
  65306. this._light = light;
  65307. this._scene = light.getScene();
  65308. light._shadowGenerator = this;
  65309. // Texture type fallback from float to int if not supported.
  65310. var caps = this._scene.getEngine().getCaps();
  65311. if (!useFullFloatFirst) {
  65312. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65313. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65314. }
  65315. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65316. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65317. }
  65318. else {
  65319. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65320. }
  65321. }
  65322. else {
  65323. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65324. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65325. }
  65326. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65327. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65328. }
  65329. else {
  65330. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65331. }
  65332. }
  65333. this._initializeGenerator();
  65334. this._applyFilterValues();
  65335. }
  65336. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65337. /**
  65338. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65339. */
  65340. get: function () {
  65341. return this._bias;
  65342. },
  65343. /**
  65344. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65345. */
  65346. set: function (bias) {
  65347. this._bias = bias;
  65348. },
  65349. enumerable: true,
  65350. configurable: true
  65351. });
  65352. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65353. /**
  65354. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65355. */
  65356. get: function () {
  65357. return this._normalBias;
  65358. },
  65359. /**
  65360. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65361. */
  65362. set: function (normalBias) {
  65363. this._normalBias = normalBias;
  65364. },
  65365. enumerable: true,
  65366. configurable: true
  65367. });
  65368. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65369. /**
  65370. * Gets the blur box offset: offset applied during the blur pass.
  65371. * Only usefull if useKernelBlur = false
  65372. */
  65373. get: function () {
  65374. return this._blurBoxOffset;
  65375. },
  65376. /**
  65377. * Sets the blur box offset: offset applied during the blur pass.
  65378. * Only usefull if useKernelBlur = false
  65379. */
  65380. set: function (value) {
  65381. if (this._blurBoxOffset === value) {
  65382. return;
  65383. }
  65384. this._blurBoxOffset = value;
  65385. this._disposeBlurPostProcesses();
  65386. },
  65387. enumerable: true,
  65388. configurable: true
  65389. });
  65390. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65391. /**
  65392. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65393. * 2 means half of the size.
  65394. */
  65395. get: function () {
  65396. return this._blurScale;
  65397. },
  65398. /**
  65399. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65400. * 2 means half of the size.
  65401. */
  65402. set: function (value) {
  65403. if (this._blurScale === value) {
  65404. return;
  65405. }
  65406. this._blurScale = value;
  65407. this._disposeBlurPostProcesses();
  65408. },
  65409. enumerable: true,
  65410. configurable: true
  65411. });
  65412. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65413. /**
  65414. * Gets the blur kernel: kernel size of the blur pass.
  65415. * Only usefull if useKernelBlur = true
  65416. */
  65417. get: function () {
  65418. return this._blurKernel;
  65419. },
  65420. /**
  65421. * Sets the blur kernel: kernel size of the blur pass.
  65422. * Only usefull if useKernelBlur = true
  65423. */
  65424. set: function (value) {
  65425. if (this._blurKernel === value) {
  65426. return;
  65427. }
  65428. this._blurKernel = value;
  65429. this._disposeBlurPostProcesses();
  65430. },
  65431. enumerable: true,
  65432. configurable: true
  65433. });
  65434. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65435. /**
  65436. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65437. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65438. */
  65439. get: function () {
  65440. return this._useKernelBlur;
  65441. },
  65442. /**
  65443. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65444. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65445. */
  65446. set: function (value) {
  65447. if (this._useKernelBlur === value) {
  65448. return;
  65449. }
  65450. this._useKernelBlur = value;
  65451. this._disposeBlurPostProcesses();
  65452. },
  65453. enumerable: true,
  65454. configurable: true
  65455. });
  65456. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65457. /**
  65458. * Gets the depth scale used in ESM mode.
  65459. */
  65460. get: function () {
  65461. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65462. },
  65463. /**
  65464. * Sets the depth scale used in ESM mode.
  65465. * This can override the scale stored on the light.
  65466. */
  65467. set: function (value) {
  65468. this._depthScale = value;
  65469. },
  65470. enumerable: true,
  65471. configurable: true
  65472. });
  65473. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65474. /**
  65475. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65476. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65477. */
  65478. get: function () {
  65479. return this._filter;
  65480. },
  65481. /**
  65482. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65483. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65484. */
  65485. set: function (value) {
  65486. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65487. if (this._light.needCube()) {
  65488. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65489. this.useExponentialShadowMap = true;
  65490. return;
  65491. }
  65492. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65493. this.useCloseExponentialShadowMap = true;
  65494. return;
  65495. }
  65496. // PCF on cubemap would also be expensive
  65497. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65498. this.usePoissonSampling = true;
  65499. return;
  65500. }
  65501. }
  65502. // Weblg1 fallback for PCF.
  65503. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65504. if (this._scene.getEngine().webGLVersion === 1) {
  65505. this.usePoissonSampling = true;
  65506. return;
  65507. }
  65508. }
  65509. if (this._filter === value) {
  65510. return;
  65511. }
  65512. this._filter = value;
  65513. this._disposeBlurPostProcesses();
  65514. this._applyFilterValues();
  65515. this._light._markMeshesAsLightDirty();
  65516. },
  65517. enumerable: true,
  65518. configurable: true
  65519. });
  65520. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65521. /**
  65522. * Gets if the current filter is set to Poisson Sampling.
  65523. */
  65524. get: function () {
  65525. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65526. },
  65527. /**
  65528. * Sets the current filter to Poisson Sampling.
  65529. */
  65530. set: function (value) {
  65531. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65532. return;
  65533. }
  65534. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65535. },
  65536. enumerable: true,
  65537. configurable: true
  65538. });
  65539. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65540. /**
  65541. * Gets if the current filter is set to VSM.
  65542. * DEPRECATED. Should use useExponentialShadowMap instead.
  65543. */
  65544. get: function () {
  65545. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65546. return this.useExponentialShadowMap;
  65547. },
  65548. /**
  65549. * Sets the current filter is to VSM.
  65550. * DEPRECATED. Should use useExponentialShadowMap instead.
  65551. */
  65552. set: function (value) {
  65553. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65554. this.useExponentialShadowMap = value;
  65555. },
  65556. enumerable: true,
  65557. configurable: true
  65558. });
  65559. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65560. /**
  65561. * Gets if the current filter is set to blurred VSM.
  65562. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65563. */
  65564. get: function () {
  65565. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65566. return this.useBlurExponentialShadowMap;
  65567. },
  65568. /**
  65569. * Sets the current filter is to blurred VSM.
  65570. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65571. */
  65572. set: function (value) {
  65573. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65574. this.useBlurExponentialShadowMap = value;
  65575. },
  65576. enumerable: true,
  65577. configurable: true
  65578. });
  65579. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65580. /**
  65581. * Gets if the current filter is set to ESM.
  65582. */
  65583. get: function () {
  65584. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65585. },
  65586. /**
  65587. * Sets the current filter is to ESM.
  65588. */
  65589. set: function (value) {
  65590. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65591. return;
  65592. }
  65593. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65594. },
  65595. enumerable: true,
  65596. configurable: true
  65597. });
  65598. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65599. /**
  65600. * Gets if the current filter is set to filtered ESM.
  65601. */
  65602. get: function () {
  65603. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65604. },
  65605. /**
  65606. * Gets if the current filter is set to filtered ESM.
  65607. */
  65608. set: function (value) {
  65609. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65610. return;
  65611. }
  65612. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65613. },
  65614. enumerable: true,
  65615. configurable: true
  65616. });
  65617. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65618. /**
  65619. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65620. * exponential to prevent steep falloff artifacts).
  65621. */
  65622. get: function () {
  65623. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65624. },
  65625. /**
  65626. * Sets the current filter to "close ESM" (using the inverse of the
  65627. * exponential to prevent steep falloff artifacts).
  65628. */
  65629. set: function (value) {
  65630. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65631. return;
  65632. }
  65633. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65634. },
  65635. enumerable: true,
  65636. configurable: true
  65637. });
  65638. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65639. /**
  65640. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65641. * exponential to prevent steep falloff artifacts).
  65642. */
  65643. get: function () {
  65644. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65645. },
  65646. /**
  65647. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65648. * exponential to prevent steep falloff artifacts).
  65649. */
  65650. set: function (value) {
  65651. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65652. return;
  65653. }
  65654. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65660. /**
  65661. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65662. */
  65663. get: function () {
  65664. return this.filter === ShadowGenerator.FILTER_PCF;
  65665. },
  65666. /**
  65667. * Sets the current filter to "PCF" (percentage closer filtering).
  65668. */
  65669. set: function (value) {
  65670. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65671. return;
  65672. }
  65673. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65674. },
  65675. enumerable: true,
  65676. configurable: true
  65677. });
  65678. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65679. /**
  65680. * Gets the PCF or PCSS Quality.
  65681. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65682. */
  65683. get: function () {
  65684. return this._filteringQuality;
  65685. },
  65686. /**
  65687. * Sets the PCF or PCSS Quality.
  65688. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65689. */
  65690. set: function (filteringQuality) {
  65691. this._filteringQuality = filteringQuality;
  65692. },
  65693. enumerable: true,
  65694. configurable: true
  65695. });
  65696. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65697. /**
  65698. * Gets if the current filter is set to "PCSS" (contact hardening).
  65699. */
  65700. get: function () {
  65701. return this.filter === ShadowGenerator.FILTER_PCSS;
  65702. },
  65703. /**
  65704. * Sets the current filter to "PCSS" (contact hardening).
  65705. */
  65706. set: function (value) {
  65707. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65708. return;
  65709. }
  65710. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65711. },
  65712. enumerable: true,
  65713. configurable: true
  65714. });
  65715. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65716. /**
  65717. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65718. * Using a ratio helps keeping shape stability independently of the map size.
  65719. *
  65720. * It does not account for the light projection as it was having too much
  65721. * instability during the light setup or during light position changes.
  65722. *
  65723. * Only valid if useContactHardeningShadow is true.
  65724. */
  65725. get: function () {
  65726. return this._contactHardeningLightSizeUVRatio;
  65727. },
  65728. /**
  65729. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65730. * Using a ratio helps keeping shape stability independently of the map size.
  65731. *
  65732. * It does not account for the light projection as it was having too much
  65733. * instability during the light setup or during light position changes.
  65734. *
  65735. * Only valid if useContactHardeningShadow is true.
  65736. */
  65737. set: function (contactHardeningLightSizeUVRatio) {
  65738. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65739. },
  65740. enumerable: true,
  65741. configurable: true
  65742. });
  65743. /**
  65744. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65745. * 0 means strongest and 1 would means no shadow.
  65746. * @returns the darkness.
  65747. */
  65748. ShadowGenerator.prototype.getDarkness = function () {
  65749. return this._darkness;
  65750. };
  65751. /**
  65752. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65753. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65754. * @returns the shadow generator allowing fluent coding.
  65755. */
  65756. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65757. if (darkness >= 1.0)
  65758. this._darkness = 1.0;
  65759. else if (darkness <= 0.0)
  65760. this._darkness = 0.0;
  65761. else
  65762. this._darkness = darkness;
  65763. return this;
  65764. };
  65765. /**
  65766. * Sets the ability to have transparent shadow (boolean).
  65767. * @param transparent True if transparent else False
  65768. * @returns the shadow generator allowing fluent coding
  65769. */
  65770. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65771. this._transparencyShadow = transparent;
  65772. return this;
  65773. };
  65774. /**
  65775. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65776. * @returns The render target texture if present otherwise, null
  65777. */
  65778. ShadowGenerator.prototype.getShadowMap = function () {
  65779. return this._shadowMap;
  65780. };
  65781. /**
  65782. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65783. * @returns The render target texture if the shadow map is present otherwise, null
  65784. */
  65785. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65786. if (this._shadowMap2) {
  65787. return this._shadowMap2;
  65788. }
  65789. return this._shadowMap;
  65790. };
  65791. /**
  65792. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65793. * @param mesh Mesh to add
  65794. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65795. * @returns the Shadow Generator itself
  65796. */
  65797. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65798. if (includeDescendants === void 0) { includeDescendants = true; }
  65799. if (!this._shadowMap) {
  65800. return this;
  65801. }
  65802. if (!this._shadowMap.renderList) {
  65803. this._shadowMap.renderList = [];
  65804. }
  65805. this._shadowMap.renderList.push(mesh);
  65806. if (includeDescendants) {
  65807. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65808. }
  65809. return this;
  65810. var _a;
  65811. };
  65812. /**
  65813. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65814. * @param mesh Mesh to remove
  65815. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65816. * @returns the Shadow Generator itself
  65817. */
  65818. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65819. if (includeDescendants === void 0) { includeDescendants = true; }
  65820. if (!this._shadowMap || !this._shadowMap.renderList) {
  65821. return this;
  65822. }
  65823. var index = this._shadowMap.renderList.indexOf(mesh);
  65824. if (index !== -1) {
  65825. this._shadowMap.renderList.splice(index, 1);
  65826. }
  65827. if (includeDescendants) {
  65828. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65829. var child = _a[_i];
  65830. this.removeShadowCaster(child);
  65831. }
  65832. }
  65833. return this;
  65834. };
  65835. /**
  65836. * Returns the associated light object.
  65837. * @returns the light generating the shadow
  65838. */
  65839. ShadowGenerator.prototype.getLight = function () {
  65840. return this._light;
  65841. };
  65842. ShadowGenerator.prototype._initializeGenerator = function () {
  65843. this._light._markMeshesAsLightDirty();
  65844. this._initializeShadowMap();
  65845. };
  65846. ShadowGenerator.prototype._initializeShadowMap = function () {
  65847. var _this = this;
  65848. // Render target
  65849. var engine = this._scene.getEngine();
  65850. if (engine.webGLVersion > 1) {
  65851. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65852. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65853. }
  65854. else {
  65855. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65856. }
  65857. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65858. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65859. this._shadowMap.anisotropicFilteringLevel = 1;
  65860. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65861. this._shadowMap.renderParticles = false;
  65862. this._shadowMap.ignoreCameraViewport = true;
  65863. // Record Face Index before render.
  65864. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65865. _this._currentFaceIndex = faceIndex;
  65866. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65867. engine.setColorWrite(false);
  65868. }
  65869. });
  65870. // Custom render function.
  65871. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65872. // Blur if required afer render.
  65873. this._shadowMap.onAfterUnbindObservable.add(function () {
  65874. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65875. engine.setColorWrite(true);
  65876. }
  65877. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65878. return;
  65879. }
  65880. var shadowMap = _this.getShadowMapForRendering();
  65881. if (shadowMap) {
  65882. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65883. }
  65884. });
  65885. // Clear according to the chosen filter.
  65886. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65887. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65888. this._shadowMap.onClearObservable.add(function (engine) {
  65889. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65890. engine.clear(clearOne, false, true, false);
  65891. }
  65892. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65893. engine.clear(clearZero, true, true, false);
  65894. }
  65895. else {
  65896. engine.clear(clearOne, true, true, false);
  65897. }
  65898. });
  65899. };
  65900. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65901. var _this = this;
  65902. var engine = this._scene.getEngine();
  65903. var targetSize = this._mapSize / this.blurScale;
  65904. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65905. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65906. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65907. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65908. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65909. }
  65910. if (this.useKernelBlur) {
  65911. 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);
  65912. this._kernelBlurXPostprocess.width = targetSize;
  65913. this._kernelBlurXPostprocess.height = targetSize;
  65914. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65915. effect.setTexture("textureSampler", _this._shadowMap);
  65916. });
  65917. 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);
  65918. this._kernelBlurXPostprocess.autoClear = false;
  65919. this._kernelBlurYPostprocess.autoClear = false;
  65920. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65921. this._kernelBlurXPostprocess.packedFloat = true;
  65922. this._kernelBlurYPostprocess.packedFloat = true;
  65923. }
  65924. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65925. }
  65926. else {
  65927. 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);
  65928. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65929. effect.setFloat2("screenSize", targetSize, targetSize);
  65930. effect.setTexture("textureSampler", _this._shadowMap);
  65931. });
  65932. this._boxBlurPostprocess.autoClear = false;
  65933. this._blurPostProcesses = [this._boxBlurPostprocess];
  65934. }
  65935. };
  65936. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65937. var index;
  65938. var engine = this._scene.getEngine();
  65939. if (depthOnlySubMeshes.length) {
  65940. engine.setColorWrite(false);
  65941. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65942. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65943. }
  65944. engine.setColorWrite(true);
  65945. }
  65946. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65947. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65948. }
  65949. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65950. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65951. }
  65952. if (this._transparencyShadow) {
  65953. for (index = 0; index < transparentSubMeshes.length; index++) {
  65954. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65955. }
  65956. }
  65957. };
  65958. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65959. var _this = this;
  65960. var mesh = subMesh.getRenderingMesh();
  65961. var scene = this._scene;
  65962. var engine = scene.getEngine();
  65963. var material = subMesh.getMaterial();
  65964. if (!material) {
  65965. return;
  65966. }
  65967. // Culling
  65968. engine.setState(material.backFaceCulling);
  65969. // Managing instances
  65970. var batch = mesh._getInstancesRenderList(subMesh._id);
  65971. if (batch.mustReturn) {
  65972. return;
  65973. }
  65974. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65975. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65976. engine.enableEffect(this._effect);
  65977. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65978. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65979. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65980. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65981. this._effect.setVector3("lightData", this._cachedDirection);
  65982. }
  65983. else {
  65984. this._effect.setVector3("lightData", this._cachedPosition);
  65985. }
  65986. if (scene.activeCamera) {
  65987. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65988. }
  65989. // Alpha test
  65990. if (material && material.needAlphaTesting()) {
  65991. var alphaTexture = material.getAlphaTestTexture();
  65992. if (alphaTexture) {
  65993. this._effect.setTexture("diffuseSampler", alphaTexture);
  65994. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65995. }
  65996. }
  65997. // Bones
  65998. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65999. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66000. }
  66001. // Morph targets
  66002. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66003. if (this.forceBackFacesOnly) {
  66004. engine.setState(true, 0, false, true);
  66005. }
  66006. // Draw
  66007. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66008. if (this.forceBackFacesOnly) {
  66009. engine.setState(true, 0, false, false);
  66010. }
  66011. }
  66012. else {
  66013. // Need to reset refresh rate of the shadowMap
  66014. if (this._shadowMap) {
  66015. this._shadowMap.resetRefreshCounter();
  66016. }
  66017. }
  66018. };
  66019. ShadowGenerator.prototype._applyFilterValues = function () {
  66020. if (!this._shadowMap) {
  66021. return;
  66022. }
  66023. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66024. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66025. }
  66026. else {
  66027. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66028. }
  66029. };
  66030. /**
  66031. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66032. * @param onCompiled Callback triggered at the and of the effects compilation
  66033. * @param options Sets of optional options forcing the compilation with different modes
  66034. */
  66035. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66036. var _this = this;
  66037. var localOptions = __assign({ useInstances: false }, options);
  66038. var shadowMap = this.getShadowMap();
  66039. if (!shadowMap) {
  66040. if (onCompiled) {
  66041. onCompiled(this);
  66042. }
  66043. return;
  66044. }
  66045. var renderList = shadowMap.renderList;
  66046. if (!renderList) {
  66047. if (onCompiled) {
  66048. onCompiled(this);
  66049. }
  66050. return;
  66051. }
  66052. var subMeshes = new Array();
  66053. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66054. var mesh = renderList_1[_i];
  66055. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66056. }
  66057. if (subMeshes.length === 0) {
  66058. if (onCompiled) {
  66059. onCompiled(this);
  66060. }
  66061. return;
  66062. }
  66063. var currentIndex = 0;
  66064. var checkReady = function () {
  66065. if (!_this._scene || !_this._scene.getEngine()) {
  66066. return;
  66067. }
  66068. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66069. currentIndex++;
  66070. if (currentIndex >= subMeshes.length) {
  66071. if (onCompiled) {
  66072. onCompiled(_this);
  66073. }
  66074. return;
  66075. }
  66076. }
  66077. setTimeout(checkReady, 16);
  66078. };
  66079. checkReady();
  66080. };
  66081. /**
  66082. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66083. * @param options Sets of optional options forcing the compilation with different modes
  66084. * @returns A promise that resolves when the compilation completes
  66085. */
  66086. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66087. var _this = this;
  66088. return new Promise(function (resolve) {
  66089. _this.forceCompilation(function () {
  66090. resolve();
  66091. }, options);
  66092. });
  66093. };
  66094. /**
  66095. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66096. * @param subMesh The submesh we want to render in the shadow map
  66097. * @param useInstances Defines wether will draw in the map using instances
  66098. * @returns true if ready otherwise, false
  66099. */
  66100. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66101. var defines = [];
  66102. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66103. defines.push("#define FLOAT");
  66104. }
  66105. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66106. defines.push("#define ESM");
  66107. }
  66108. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66109. defines.push("#define DEPTHTEXTURE");
  66110. }
  66111. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66112. var mesh = subMesh.getMesh();
  66113. var material = subMesh.getMaterial();
  66114. // Normal bias.
  66115. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66116. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66117. defines.push("#define NORMAL");
  66118. if (mesh.nonUniformScaling) {
  66119. defines.push("#define NONUNIFORMSCALING");
  66120. }
  66121. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66122. defines.push("#define DIRECTIONINLIGHTDATA");
  66123. }
  66124. }
  66125. // Alpha test
  66126. if (material && material.needAlphaTesting()) {
  66127. var alphaTexture = material.getAlphaTestTexture();
  66128. if (alphaTexture) {
  66129. defines.push("#define ALPHATEST");
  66130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66131. attribs.push(BABYLON.VertexBuffer.UVKind);
  66132. defines.push("#define UV1");
  66133. }
  66134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66135. if (alphaTexture.coordinatesIndex === 1) {
  66136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66137. defines.push("#define UV2");
  66138. }
  66139. }
  66140. }
  66141. }
  66142. // Bones
  66143. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66144. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66145. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66146. if (mesh.numBoneInfluencers > 4) {
  66147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66149. }
  66150. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66151. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66152. }
  66153. else {
  66154. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66155. }
  66156. // Morph targets
  66157. var manager = mesh.morphTargetManager;
  66158. var morphInfluencers = 0;
  66159. if (manager) {
  66160. if (manager.numInfluencers > 0) {
  66161. defines.push("#define MORPHTARGETS");
  66162. morphInfluencers = manager.numInfluencers;
  66163. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66164. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66165. }
  66166. }
  66167. // Instances
  66168. if (useInstances) {
  66169. defines.push("#define INSTANCES");
  66170. attribs.push("world0");
  66171. attribs.push("world1");
  66172. attribs.push("world2");
  66173. attribs.push("world3");
  66174. }
  66175. // Get correct effect
  66176. var join = defines.join("\n");
  66177. if (this._cachedDefines !== join) {
  66178. this._cachedDefines = join;
  66179. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66180. }
  66181. if (!this._effect.isReady()) {
  66182. return false;
  66183. }
  66184. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66185. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66186. this._initializeBlurRTTAndPostProcesses();
  66187. }
  66188. }
  66189. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66190. return false;
  66191. }
  66192. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66193. return false;
  66194. }
  66195. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66196. return false;
  66197. }
  66198. return true;
  66199. };
  66200. /**
  66201. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66202. * @param defines Defines of the material we want to update
  66203. * @param lightIndex Index of the light in the enabled light list of the material
  66204. */
  66205. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66206. var scene = this._scene;
  66207. var light = this._light;
  66208. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66209. return;
  66210. }
  66211. defines["SHADOW" + lightIndex] = true;
  66212. if (this.useContactHardeningShadow) {
  66213. defines["SHADOWPCSS" + lightIndex] = true;
  66214. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66215. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66216. }
  66217. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66218. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66219. }
  66220. // else default to high.
  66221. }
  66222. if (this.usePercentageCloserFiltering) {
  66223. defines["SHADOWPCF" + lightIndex] = true;
  66224. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66225. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66226. }
  66227. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66228. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66229. }
  66230. // else default to high.
  66231. }
  66232. else if (this.usePoissonSampling) {
  66233. defines["SHADOWPOISSON" + lightIndex] = true;
  66234. }
  66235. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66236. defines["SHADOWESM" + lightIndex] = true;
  66237. }
  66238. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66239. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66240. }
  66241. if (light.needCube()) {
  66242. defines["SHADOWCUBE" + lightIndex] = true;
  66243. }
  66244. };
  66245. /**
  66246. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66247. * defined in the generator but impacting the effect).
  66248. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66249. * @param effect The effect we are binfing the information for
  66250. */
  66251. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66252. var light = this._light;
  66253. var scene = this._scene;
  66254. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66255. return;
  66256. }
  66257. var camera = scene.activeCamera;
  66258. if (!camera) {
  66259. return;
  66260. }
  66261. var shadowMap = this.getShadowMap();
  66262. if (!shadowMap) {
  66263. return;
  66264. }
  66265. if (!light.needCube()) {
  66266. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66267. }
  66268. // Only PCF uses depth stencil texture.
  66269. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66270. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66271. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66272. }
  66273. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66274. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66275. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66276. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66277. }
  66278. else {
  66279. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66280. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66281. }
  66282. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66283. };
  66284. /**
  66285. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66286. * (eq to shadow prjection matrix * light transform matrix)
  66287. * @returns The transform matrix used to create the shadow map
  66288. */
  66289. ShadowGenerator.prototype.getTransformMatrix = function () {
  66290. var scene = this._scene;
  66291. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66292. return this._transformMatrix;
  66293. }
  66294. this._currentRenderID = scene.getRenderId();
  66295. this._currentFaceIndexCache = this._currentFaceIndex;
  66296. var lightPosition = this._light.position;
  66297. if (this._light.computeTransformedInformation()) {
  66298. lightPosition = this._light.transformedPosition;
  66299. }
  66300. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66301. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66302. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66303. }
  66304. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66305. this._cachedPosition.copyFrom(lightPosition);
  66306. this._cachedDirection.copyFrom(this._lightDirection);
  66307. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66308. var shadowMap = this.getShadowMap();
  66309. if (shadowMap) {
  66310. var renderList = shadowMap.renderList;
  66311. if (renderList) {
  66312. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66313. }
  66314. }
  66315. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66316. }
  66317. return this._transformMatrix;
  66318. };
  66319. /**
  66320. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66321. * Cube and 2D textures for instance.
  66322. */
  66323. ShadowGenerator.prototype.recreateShadowMap = function () {
  66324. var shadowMap = this._shadowMap;
  66325. if (!shadowMap) {
  66326. return;
  66327. }
  66328. // Track render list.
  66329. var renderList = shadowMap.renderList;
  66330. // Clean up existing data.
  66331. this._disposeRTTandPostProcesses();
  66332. // Reinitializes.
  66333. this._initializeGenerator();
  66334. // Reaffect the filter to ensure a correct fallback if necessary.
  66335. this.filter = this.filter;
  66336. // Reaffect the filter.
  66337. this._applyFilterValues();
  66338. // Reaffect Render List.
  66339. this._shadowMap.renderList = renderList;
  66340. };
  66341. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66342. if (this._shadowMap2) {
  66343. this._shadowMap2.dispose();
  66344. this._shadowMap2 = null;
  66345. }
  66346. if (this._boxBlurPostprocess) {
  66347. this._boxBlurPostprocess.dispose();
  66348. this._boxBlurPostprocess = null;
  66349. }
  66350. if (this._kernelBlurXPostprocess) {
  66351. this._kernelBlurXPostprocess.dispose();
  66352. this._kernelBlurXPostprocess = null;
  66353. }
  66354. if (this._kernelBlurYPostprocess) {
  66355. this._kernelBlurYPostprocess.dispose();
  66356. this._kernelBlurYPostprocess = null;
  66357. }
  66358. this._blurPostProcesses = [];
  66359. };
  66360. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66361. if (this._shadowMap) {
  66362. this._shadowMap.dispose();
  66363. this._shadowMap = null;
  66364. }
  66365. this._disposeBlurPostProcesses();
  66366. };
  66367. /**
  66368. * Disposes the ShadowGenerator.
  66369. * Returns nothing.
  66370. */
  66371. ShadowGenerator.prototype.dispose = function () {
  66372. this._disposeRTTandPostProcesses();
  66373. if (this._light) {
  66374. this._light._shadowGenerator = null;
  66375. this._light._markMeshesAsLightDirty();
  66376. }
  66377. };
  66378. /**
  66379. * Serializes the shadow generator setup to a json object.
  66380. * @returns The serialized JSON object
  66381. */
  66382. ShadowGenerator.prototype.serialize = function () {
  66383. var serializationObject = {};
  66384. var shadowMap = this.getShadowMap();
  66385. if (!shadowMap) {
  66386. return serializationObject;
  66387. }
  66388. serializationObject.lightId = this._light.id;
  66389. serializationObject.mapSize = shadowMap.getRenderSize();
  66390. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66391. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66392. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66393. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66394. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66395. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66396. serializationObject.depthScale = this.depthScale;
  66397. serializationObject.darkness = this.getDarkness();
  66398. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66399. serializationObject.blurKernel = this.blurKernel;
  66400. serializationObject.blurScale = this.blurScale;
  66401. serializationObject.useKernelBlur = this.useKernelBlur;
  66402. serializationObject.transparencyShadow = this._transparencyShadow;
  66403. serializationObject.bias = this.bias;
  66404. serializationObject.normalBias = this.normalBias;
  66405. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66406. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66407. serializationObject.filteringQuality = this.filteringQuality;
  66408. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66409. serializationObject.renderList = [];
  66410. if (shadowMap.renderList) {
  66411. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66412. var mesh = shadowMap.renderList[meshIndex];
  66413. serializationObject.renderList.push(mesh.id);
  66414. }
  66415. }
  66416. return serializationObject;
  66417. };
  66418. /**
  66419. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66420. * @param parsedShadowGenerator The JSON object to parse
  66421. * @param scene The scene to create the shadow map for
  66422. * @returns The parsed shadow generator
  66423. */
  66424. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66425. //casting to point light, as light is missing the position attr and typescript complains.
  66426. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66427. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66428. var shadowMap = shadowGenerator.getShadowMap();
  66429. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66430. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66431. meshes.forEach(function (mesh) {
  66432. if (!shadowMap) {
  66433. return;
  66434. }
  66435. if (!shadowMap.renderList) {
  66436. shadowMap.renderList = [];
  66437. }
  66438. shadowMap.renderList.push(mesh);
  66439. });
  66440. }
  66441. if (parsedShadowGenerator.usePoissonSampling) {
  66442. shadowGenerator.usePoissonSampling = true;
  66443. }
  66444. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66445. shadowGenerator.useExponentialShadowMap = true;
  66446. }
  66447. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66448. shadowGenerator.useBlurExponentialShadowMap = true;
  66449. }
  66450. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66451. shadowGenerator.useCloseExponentialShadowMap = true;
  66452. }
  66453. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66454. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66455. }
  66456. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66457. shadowGenerator.usePercentageCloserFiltering = true;
  66458. }
  66459. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66460. shadowGenerator.useContactHardeningShadow = true;
  66461. }
  66462. if (parsedShadowGenerator.filteringQuality) {
  66463. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66464. }
  66465. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66466. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66467. }
  66468. // Backward compat
  66469. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66470. shadowGenerator.useExponentialShadowMap = true;
  66471. }
  66472. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66473. shadowGenerator.useBlurExponentialShadowMap = true;
  66474. }
  66475. if (parsedShadowGenerator.depthScale) {
  66476. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66477. }
  66478. if (parsedShadowGenerator.blurScale) {
  66479. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66480. }
  66481. if (parsedShadowGenerator.blurBoxOffset) {
  66482. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66483. }
  66484. if (parsedShadowGenerator.useKernelBlur) {
  66485. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66486. }
  66487. if (parsedShadowGenerator.blurKernel) {
  66488. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66489. }
  66490. if (parsedShadowGenerator.bias !== undefined) {
  66491. shadowGenerator.bias = parsedShadowGenerator.bias;
  66492. }
  66493. if (parsedShadowGenerator.normalBias !== undefined) {
  66494. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66495. }
  66496. if (parsedShadowGenerator.darkness) {
  66497. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66498. }
  66499. if (parsedShadowGenerator.transparencyShadow) {
  66500. shadowGenerator.setTransparencyShadow(true);
  66501. }
  66502. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66503. return shadowGenerator;
  66504. };
  66505. /**
  66506. * Shadow generator mode None: no filtering applied.
  66507. */
  66508. ShadowGenerator.FILTER_NONE = 0;
  66509. /**
  66510. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66511. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66512. */
  66513. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66514. /**
  66515. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66516. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66517. */
  66518. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66519. /**
  66520. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66521. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66522. */
  66523. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66524. /**
  66525. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66526. * edge artifacts on steep falloff.
  66527. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66528. */
  66529. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66530. /**
  66531. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66532. * edge artifacts on steep falloff.
  66533. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66534. */
  66535. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66536. /**
  66537. * Shadow generator mode PCF: Percentage Closer Filtering
  66538. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66539. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66540. */
  66541. ShadowGenerator.FILTER_PCF = 6;
  66542. /**
  66543. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66544. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66545. * Contact Hardening
  66546. */
  66547. ShadowGenerator.FILTER_PCSS = 7;
  66548. /**
  66549. * Reserved for PCF and PCSS
  66550. * Highest Quality.
  66551. *
  66552. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66553. *
  66554. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66555. */
  66556. ShadowGenerator.QUALITY_HIGH = 0;
  66557. /**
  66558. * Reserved for PCF and PCSS
  66559. * Good tradeoff for quality/perf cross devices
  66560. *
  66561. * Execute PCF on a 3*3 kernel.
  66562. *
  66563. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66564. */
  66565. ShadowGenerator.QUALITY_MEDIUM = 1;
  66566. /**
  66567. * Reserved for PCF and PCSS
  66568. * The lowest quality but the fastest.
  66569. *
  66570. * Execute PCF on a 1*1 kernel.
  66571. *
  66572. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66573. */
  66574. ShadowGenerator.QUALITY_LOW = 2;
  66575. return ShadowGenerator;
  66576. }());
  66577. BABYLON.ShadowGenerator = ShadowGenerator;
  66578. })(BABYLON || (BABYLON = {}));
  66579. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66580. var BABYLON;
  66581. (function (BABYLON) {
  66582. var DefaultLoadingScreen = /** @class */ (function () {
  66583. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66584. if (_loadingText === void 0) { _loadingText = ""; }
  66585. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66586. var _this = this;
  66587. this._renderingCanvas = _renderingCanvas;
  66588. this._loadingText = _loadingText;
  66589. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66590. // Resize
  66591. this._resizeLoadingUI = function () {
  66592. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66593. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66594. if (!_this._loadingDiv) {
  66595. return;
  66596. }
  66597. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66598. _this._loadingDiv.style.left = canvasRect.left + "px";
  66599. _this._loadingDiv.style.top = canvasRect.top + "px";
  66600. _this._loadingDiv.style.width = canvasRect.width + "px";
  66601. _this._loadingDiv.style.height = canvasRect.height + "px";
  66602. };
  66603. }
  66604. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66605. if (this._loadingDiv) {
  66606. // Do not add a loading screen if there is already one
  66607. return;
  66608. }
  66609. this._loadingDiv = document.createElement("div");
  66610. this._loadingDiv.id = "babylonjsLoadingDiv";
  66611. this._loadingDiv.style.opacity = "0";
  66612. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66613. this._loadingDiv.style.pointerEvents = "none";
  66614. // Loading text
  66615. this._loadingTextDiv = document.createElement("div");
  66616. this._loadingTextDiv.style.position = "absolute";
  66617. this._loadingTextDiv.style.left = "0";
  66618. this._loadingTextDiv.style.top = "50%";
  66619. this._loadingTextDiv.style.marginTop = "80px";
  66620. this._loadingTextDiv.style.width = "100%";
  66621. this._loadingTextDiv.style.height = "20px";
  66622. this._loadingTextDiv.style.fontFamily = "Arial";
  66623. this._loadingTextDiv.style.fontSize = "14px";
  66624. this._loadingTextDiv.style.color = "white";
  66625. this._loadingTextDiv.style.textAlign = "center";
  66626. this._loadingTextDiv.innerHTML = "Loading";
  66627. this._loadingDiv.appendChild(this._loadingTextDiv);
  66628. //set the predefined text
  66629. this._loadingTextDiv.innerHTML = this._loadingText;
  66630. // Generating keyframes
  66631. var style = document.createElement('style');
  66632. style.type = 'text/css';
  66633. 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 }";
  66634. style.innerHTML = keyFrames;
  66635. document.getElementsByTagName('head')[0].appendChild(style);
  66636. // Loading img
  66637. var imgBack = new Image();
  66638. 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";
  66639. imgBack.style.position = "absolute";
  66640. imgBack.style.left = "50%";
  66641. imgBack.style.top = "50%";
  66642. imgBack.style.marginLeft = "-60px";
  66643. imgBack.style.marginTop = "-60px";
  66644. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66645. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66646. imgBack.style.transformOrigin = "50% 50%";
  66647. imgBack.style.webkitTransformOrigin = "50% 50%";
  66648. this._loadingDiv.appendChild(imgBack);
  66649. this._resizeLoadingUI();
  66650. window.addEventListener("resize", this._resizeLoadingUI);
  66651. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66652. document.body.appendChild(this._loadingDiv);
  66653. this._loadingDiv.style.opacity = "1";
  66654. };
  66655. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66656. var _this = this;
  66657. if (!this._loadingDiv) {
  66658. return;
  66659. }
  66660. var onTransitionEnd = function () {
  66661. if (!_this._loadingDiv) {
  66662. return;
  66663. }
  66664. document.body.removeChild(_this._loadingDiv);
  66665. window.removeEventListener("resize", _this._resizeLoadingUI);
  66666. _this._loadingDiv = null;
  66667. };
  66668. this._loadingDiv.style.opacity = "0";
  66669. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66670. };
  66671. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66672. set: function (text) {
  66673. this._loadingText = text;
  66674. if (this._loadingTextDiv) {
  66675. this._loadingTextDiv.innerHTML = this._loadingText;
  66676. }
  66677. },
  66678. enumerable: true,
  66679. configurable: true
  66680. });
  66681. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66682. get: function () {
  66683. return this._loadingDivBackgroundColor;
  66684. },
  66685. set: function (color) {
  66686. this._loadingDivBackgroundColor = color;
  66687. if (!this._loadingDiv) {
  66688. return;
  66689. }
  66690. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66691. },
  66692. enumerable: true,
  66693. configurable: true
  66694. });
  66695. return DefaultLoadingScreen;
  66696. }());
  66697. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66698. })(BABYLON || (BABYLON = {}));
  66699. //# sourceMappingURL=babylon.loadingScreen.js.map
  66700. var BABYLON;
  66701. (function (BABYLON) {
  66702. var SceneLoaderProgressEvent = /** @class */ (function () {
  66703. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66704. this.lengthComputable = lengthComputable;
  66705. this.loaded = loaded;
  66706. this.total = total;
  66707. }
  66708. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66709. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66710. };
  66711. return SceneLoaderProgressEvent;
  66712. }());
  66713. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66714. var SceneLoader = /** @class */ (function () {
  66715. function SceneLoader() {
  66716. }
  66717. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66718. get: function () {
  66719. return 0;
  66720. },
  66721. enumerable: true,
  66722. configurable: true
  66723. });
  66724. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66725. get: function () {
  66726. return 1;
  66727. },
  66728. enumerable: true,
  66729. configurable: true
  66730. });
  66731. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66732. get: function () {
  66733. return 2;
  66734. },
  66735. enumerable: true,
  66736. configurable: true
  66737. });
  66738. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66739. get: function () {
  66740. return 3;
  66741. },
  66742. enumerable: true,
  66743. configurable: true
  66744. });
  66745. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66746. get: function () {
  66747. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66748. },
  66749. set: function (value) {
  66750. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66751. },
  66752. enumerable: true,
  66753. configurable: true
  66754. });
  66755. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66756. get: function () {
  66757. return SceneLoader._ShowLoadingScreen;
  66758. },
  66759. set: function (value) {
  66760. SceneLoader._ShowLoadingScreen = value;
  66761. },
  66762. enumerable: true,
  66763. configurable: true
  66764. });
  66765. Object.defineProperty(SceneLoader, "loggingLevel", {
  66766. get: function () {
  66767. return SceneLoader._loggingLevel;
  66768. },
  66769. set: function (value) {
  66770. SceneLoader._loggingLevel = value;
  66771. },
  66772. enumerable: true,
  66773. configurable: true
  66774. });
  66775. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66776. get: function () {
  66777. return SceneLoader._CleanBoneMatrixWeights;
  66778. },
  66779. set: function (value) {
  66780. SceneLoader._CleanBoneMatrixWeights = value;
  66781. },
  66782. enumerable: true,
  66783. configurable: true
  66784. });
  66785. SceneLoader._getDefaultPlugin = function () {
  66786. return SceneLoader._registeredPlugins[".babylon"];
  66787. };
  66788. SceneLoader._getPluginForExtension = function (extension) {
  66789. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66790. if (registeredPlugin) {
  66791. return registeredPlugin;
  66792. }
  66793. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66794. return SceneLoader._getDefaultPlugin();
  66795. };
  66796. SceneLoader._getPluginForDirectLoad = function (data) {
  66797. for (var extension in SceneLoader._registeredPlugins) {
  66798. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66799. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66800. return SceneLoader._registeredPlugins[extension];
  66801. }
  66802. }
  66803. return SceneLoader._getDefaultPlugin();
  66804. };
  66805. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66806. if (sceneFilename.name) {
  66807. sceneFilename = sceneFilename.name;
  66808. }
  66809. var queryStringPosition = sceneFilename.indexOf("?");
  66810. if (queryStringPosition !== -1) {
  66811. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66812. }
  66813. var dotPosition = sceneFilename.lastIndexOf(".");
  66814. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66815. return SceneLoader._getPluginForExtension(extension);
  66816. };
  66817. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66818. SceneLoader._getDirectLoad = function (sceneFilename) {
  66819. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66820. return sceneFilename.substr(5);
  66821. }
  66822. return null;
  66823. };
  66824. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66825. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66826. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66827. var plugin;
  66828. if (registeredPlugin.plugin.createPlugin) {
  66829. plugin = registeredPlugin.plugin.createPlugin();
  66830. }
  66831. else {
  66832. plugin = registeredPlugin.plugin;
  66833. }
  66834. var useArrayBuffer = registeredPlugin.isBinary;
  66835. var database;
  66836. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66837. var dataCallback = function (data, responseURL) {
  66838. if (scene.isDisposed) {
  66839. onError("Scene has been disposed");
  66840. return;
  66841. }
  66842. scene.database = database;
  66843. onSuccess(plugin, data, responseURL);
  66844. };
  66845. var request = null;
  66846. var pluginDisposed = false;
  66847. var onDisposeObservable = plugin.onDisposeObservable;
  66848. if (onDisposeObservable) {
  66849. onDisposeObservable.add(function () {
  66850. pluginDisposed = true;
  66851. if (request) {
  66852. request.abort();
  66853. request = null;
  66854. }
  66855. onDispose();
  66856. });
  66857. }
  66858. var manifestChecked = function () {
  66859. if (pluginDisposed) {
  66860. return;
  66861. }
  66862. var url = rootUrl + sceneFilename;
  66863. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66864. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66865. } : undefined, database, useArrayBuffer, function (request, exception) {
  66866. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66867. });
  66868. };
  66869. if (directLoad) {
  66870. dataCallback(directLoad);
  66871. return plugin;
  66872. }
  66873. if (rootUrl.indexOf("file:") === -1) {
  66874. var engine = scene.getEngine();
  66875. var canUseOfflineSupport = engine.enableOfflineSupport;
  66876. if (canUseOfflineSupport) {
  66877. // Also check for exceptions
  66878. var exceptionFound = false;
  66879. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66880. var regex = _a[_i];
  66881. if (regex.test(rootUrl + sceneFilename)) {
  66882. exceptionFound = true;
  66883. break;
  66884. }
  66885. }
  66886. canUseOfflineSupport = !exceptionFound;
  66887. }
  66888. if (canUseOfflineSupport) {
  66889. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66890. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66891. }
  66892. else {
  66893. manifestChecked();
  66894. }
  66895. }
  66896. // Loading file from disk via input file or drag'n'drop
  66897. else {
  66898. var fileOrString = sceneFilename;
  66899. if (fileOrString.name) { // File
  66900. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66901. }
  66902. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66903. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66904. }
  66905. else {
  66906. onError("Unable to find file named " + sceneFilename);
  66907. }
  66908. }
  66909. return plugin;
  66910. };
  66911. // Public functions
  66912. SceneLoader.GetPluginForExtension = function (extension) {
  66913. return SceneLoader._getPluginForExtension(extension).plugin;
  66914. };
  66915. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66916. return !!SceneLoader._registeredPlugins[extension];
  66917. };
  66918. SceneLoader.RegisterPlugin = function (plugin) {
  66919. if (typeof plugin.extensions === "string") {
  66920. var extension = plugin.extensions;
  66921. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66922. plugin: plugin,
  66923. isBinary: false
  66924. };
  66925. }
  66926. else {
  66927. var extensions = plugin.extensions;
  66928. Object.keys(extensions).forEach(function (extension) {
  66929. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66930. plugin: plugin,
  66931. isBinary: extensions[extension].isBinary
  66932. };
  66933. });
  66934. }
  66935. };
  66936. /**
  66937. * Import meshes into a scene
  66938. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66939. * @param rootUrl a string that defines the root url for scene and resources
  66940. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66941. * @param scene the instance of BABYLON.Scene to append to
  66942. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66943. * @param onProgress a callback with a progress event for each file being loaded
  66944. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66945. * @param pluginExtension the extension used to determine the plugin
  66946. * @returns The loaded plugin
  66947. */
  66948. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66949. if (onSuccess === void 0) { onSuccess = null; }
  66950. if (onProgress === void 0) { onProgress = null; }
  66951. if (onError === void 0) { onError = null; }
  66952. if (pluginExtension === void 0) { pluginExtension = null; }
  66953. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66954. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66955. return null;
  66956. }
  66957. var loadingToken = {};
  66958. scene._addPendingData(loadingToken);
  66959. var disposeHandler = function () {
  66960. scene._removePendingData(loadingToken);
  66961. };
  66962. var errorHandler = function (message, exception) {
  66963. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66964. if (onError) {
  66965. onError(scene, errorMessage, exception);
  66966. }
  66967. else {
  66968. BABYLON.Tools.Error(errorMessage);
  66969. // should the exception be thrown?
  66970. }
  66971. disposeHandler();
  66972. };
  66973. var progressHandler = onProgress ? function (event) {
  66974. try {
  66975. onProgress(event);
  66976. }
  66977. catch (e) {
  66978. errorHandler("Error in onProgress callback", e);
  66979. }
  66980. } : undefined;
  66981. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66982. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66983. if (onSuccess) {
  66984. try {
  66985. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66986. }
  66987. catch (e) {
  66988. errorHandler("Error in onSuccess callback", e);
  66989. }
  66990. }
  66991. scene._removePendingData(loadingToken);
  66992. };
  66993. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66994. if (plugin.rewriteRootURL) {
  66995. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66996. }
  66997. if (sceneFilename === "") {
  66998. if (sceneFilename === "") {
  66999. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67000. }
  67001. }
  67002. if (plugin.importMesh) {
  67003. var syncedPlugin = plugin;
  67004. var meshes = new Array();
  67005. var particleSystems = new Array();
  67006. var skeletons = new Array();
  67007. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67008. return;
  67009. }
  67010. scene.loadingPluginName = plugin.name;
  67011. successHandler(meshes, particleSystems, skeletons, []);
  67012. }
  67013. else {
  67014. var asyncedPlugin = plugin;
  67015. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67016. scene.loadingPluginName = plugin.name;
  67017. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67018. }).catch(function (error) {
  67019. errorHandler(error.message, error);
  67020. });
  67021. }
  67022. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67023. };
  67024. /**
  67025. * Import meshes into a scene
  67026. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67027. * @param rootUrl a string that defines the root url for scene and resources
  67028. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67029. * @param scene the instance of BABYLON.Scene to append to
  67030. * @param onProgress a callback with a progress event for each file being loaded
  67031. * @param pluginExtension the extension used to determine the plugin
  67032. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67033. */
  67034. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67035. if (onProgress === void 0) { onProgress = null; }
  67036. if (pluginExtension === void 0) { pluginExtension = null; }
  67037. return new Promise(function (resolve, reject) {
  67038. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67039. resolve({
  67040. meshes: meshes,
  67041. particleSystems: particleSystems,
  67042. skeletons: skeletons,
  67043. animationGroups: animationGroups
  67044. });
  67045. }, onProgress, function (scene, message, exception) {
  67046. reject(exception || new Error(message));
  67047. }, pluginExtension);
  67048. });
  67049. };
  67050. /**
  67051. * Load a scene
  67052. * @param rootUrl a string that defines the root url for scene and resources
  67053. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67054. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67055. * @param onSuccess a callback with the scene when import succeeds
  67056. * @param onProgress a callback with a progress event for each file being loaded
  67057. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67058. * @param pluginExtension the extension used to determine the plugin
  67059. * @returns The loaded plugin
  67060. */
  67061. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67062. if (onSuccess === void 0) { onSuccess = null; }
  67063. if (onProgress === void 0) { onProgress = null; }
  67064. if (onError === void 0) { onError = null; }
  67065. if (pluginExtension === void 0) { pluginExtension = null; }
  67066. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67067. };
  67068. /**
  67069. * Load a scene
  67070. * @param rootUrl a string that defines the root url for scene and resources
  67071. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67072. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67073. * @param onProgress a callback with a progress event for each file being loaded
  67074. * @param pluginExtension the extension used to determine the plugin
  67075. * @returns The loaded scene
  67076. */
  67077. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67078. if (onProgress === void 0) { onProgress = null; }
  67079. if (pluginExtension === void 0) { pluginExtension = null; }
  67080. return new Promise(function (resolve, reject) {
  67081. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67082. resolve(scene);
  67083. }, onProgress, function (scene, message, exception) {
  67084. reject(exception || new Error(message));
  67085. }, pluginExtension);
  67086. });
  67087. };
  67088. /**
  67089. * Append a scene
  67090. * @param rootUrl a string that defines the root url for scene and resources
  67091. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67092. * @param scene is the instance of BABYLON.Scene to append to
  67093. * @param onSuccess a callback with the scene when import succeeds
  67094. * @param onProgress a callback with a progress event for each file being loaded
  67095. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67096. * @param pluginExtension the extension used to determine the plugin
  67097. * @returns The loaded plugin
  67098. */
  67099. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67100. if (onSuccess === void 0) { onSuccess = null; }
  67101. if (onProgress === void 0) { onProgress = null; }
  67102. if (onError === void 0) { onError = null; }
  67103. if (pluginExtension === void 0) { pluginExtension = null; }
  67104. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67105. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67106. return null;
  67107. }
  67108. if (SceneLoader.ShowLoadingScreen) {
  67109. scene.getEngine().displayLoadingUI();
  67110. }
  67111. var loadingToken = {};
  67112. scene._addPendingData(loadingToken);
  67113. var disposeHandler = function () {
  67114. scene._removePendingData(loadingToken);
  67115. scene.getEngine().hideLoadingUI();
  67116. };
  67117. var errorHandler = function (message, exception) {
  67118. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67119. if (onError) {
  67120. onError(scene, errorMessage, exception);
  67121. }
  67122. else {
  67123. BABYLON.Tools.Error(errorMessage);
  67124. // should the exception be thrown?
  67125. }
  67126. disposeHandler();
  67127. };
  67128. var progressHandler = onProgress ? function (event) {
  67129. try {
  67130. onProgress(event);
  67131. }
  67132. catch (e) {
  67133. errorHandler("Error in onProgress callback", e);
  67134. }
  67135. } : undefined;
  67136. var successHandler = function () {
  67137. if (onSuccess) {
  67138. try {
  67139. onSuccess(scene);
  67140. }
  67141. catch (e) {
  67142. errorHandler("Error in onSuccess callback", e);
  67143. }
  67144. }
  67145. scene._removePendingData(loadingToken);
  67146. };
  67147. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67148. if (sceneFilename === "") {
  67149. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67150. }
  67151. if (plugin.load) {
  67152. var syncedPlugin = plugin;
  67153. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67154. return;
  67155. }
  67156. scene.loadingPluginName = plugin.name;
  67157. successHandler();
  67158. }
  67159. else {
  67160. var asyncedPlugin = plugin;
  67161. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67162. scene.loadingPluginName = plugin.name;
  67163. successHandler();
  67164. }).catch(function (error) {
  67165. errorHandler(error.message, error);
  67166. });
  67167. }
  67168. if (SceneLoader.ShowLoadingScreen) {
  67169. scene.executeWhenReady(function () {
  67170. scene.getEngine().hideLoadingUI();
  67171. });
  67172. }
  67173. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67174. };
  67175. /**
  67176. * Append a scene
  67177. * @param rootUrl a string that defines the root url for scene and resources
  67178. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67179. * @param scene is the instance of BABYLON.Scene to append to
  67180. * @param onProgress a callback with a progress event for each file being loaded
  67181. * @param pluginExtension the extension used to determine the plugin
  67182. * @returns The given scene
  67183. */
  67184. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67185. if (onProgress === void 0) { onProgress = null; }
  67186. if (pluginExtension === void 0) { pluginExtension = null; }
  67187. return new Promise(function (resolve, reject) {
  67188. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67189. resolve(scene);
  67190. }, onProgress, function (scene, message, exception) {
  67191. reject(exception || new Error(message));
  67192. }, pluginExtension);
  67193. });
  67194. };
  67195. /**
  67196. * Load a scene into an asset container
  67197. * @param rootUrl a string that defines the root url for scene and resources
  67198. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67199. * @param scene is the instance of BABYLON.Scene to append to
  67200. * @param onSuccess a callback with the scene when import succeeds
  67201. * @param onProgress a callback with a progress event for each file being loaded
  67202. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67203. * @param pluginExtension the extension used to determine the plugin
  67204. * @returns The loaded plugin
  67205. */
  67206. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67207. if (onSuccess === void 0) { onSuccess = null; }
  67208. if (onProgress === void 0) { onProgress = null; }
  67209. if (onError === void 0) { onError = null; }
  67210. if (pluginExtension === void 0) { pluginExtension = null; }
  67211. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67212. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67213. return null;
  67214. }
  67215. var loadingToken = {};
  67216. scene._addPendingData(loadingToken);
  67217. var disposeHandler = function () {
  67218. scene._removePendingData(loadingToken);
  67219. };
  67220. var errorHandler = function (message, exception) {
  67221. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67222. if (onError) {
  67223. onError(scene, errorMessage, exception);
  67224. }
  67225. else {
  67226. BABYLON.Tools.Error(errorMessage);
  67227. // should the exception be thrown?
  67228. }
  67229. disposeHandler();
  67230. };
  67231. var progressHandler = onProgress ? function (event) {
  67232. try {
  67233. onProgress(event);
  67234. }
  67235. catch (e) {
  67236. errorHandler("Error in onProgress callback", e);
  67237. }
  67238. } : undefined;
  67239. var successHandler = function (assets) {
  67240. if (onSuccess) {
  67241. try {
  67242. onSuccess(assets);
  67243. }
  67244. catch (e) {
  67245. errorHandler("Error in onSuccess callback", e);
  67246. }
  67247. }
  67248. scene._removePendingData(loadingToken);
  67249. };
  67250. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67251. if (plugin.loadAssetContainer) {
  67252. var syncedPlugin = plugin;
  67253. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67254. if (!assetContainer) {
  67255. return;
  67256. }
  67257. scene.loadingPluginName = plugin.name;
  67258. successHandler(assetContainer);
  67259. }
  67260. else if (plugin.loadAssetContainerAsync) {
  67261. var asyncedPlugin = plugin;
  67262. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67263. scene.loadingPluginName = plugin.name;
  67264. successHandler(assetContainer);
  67265. }).catch(function (error) {
  67266. errorHandler(error.message, error);
  67267. });
  67268. }
  67269. else {
  67270. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67271. }
  67272. if (SceneLoader.ShowLoadingScreen) {
  67273. scene.executeWhenReady(function () {
  67274. scene.getEngine().hideLoadingUI();
  67275. });
  67276. }
  67277. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67278. };
  67279. /**
  67280. * Load a scene into an asset container
  67281. * @param rootUrl a string that defines the root url for scene and resources
  67282. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67283. * @param scene is the instance of BABYLON.Scene to append to
  67284. * @param onProgress a callback with a progress event for each file being loaded
  67285. * @param pluginExtension the extension used to determine the plugin
  67286. * @returns The loaded asset container
  67287. */
  67288. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67289. if (onProgress === void 0) { onProgress = null; }
  67290. if (pluginExtension === void 0) { pluginExtension = null; }
  67291. return new Promise(function (resolve, reject) {
  67292. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67293. resolve(assetContainer);
  67294. }, onProgress, function (scene, message, exception) {
  67295. reject(exception || new Error(message));
  67296. }, pluginExtension);
  67297. });
  67298. };
  67299. // Flags
  67300. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67301. SceneLoader._ShowLoadingScreen = true;
  67302. SceneLoader._CleanBoneMatrixWeights = false;
  67303. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67304. // Members
  67305. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67306. SceneLoader._registeredPlugins = {};
  67307. return SceneLoader;
  67308. }());
  67309. BABYLON.SceneLoader = SceneLoader;
  67310. ;
  67311. })(BABYLON || (BABYLON = {}));
  67312. //# sourceMappingURL=babylon.sceneLoader.js.map
  67313. var BABYLON;
  67314. (function (BABYLON) {
  67315. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67316. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67317. var parsedMaterial = parsedData.materials[index];
  67318. if (parsedMaterial.id === id) {
  67319. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67320. }
  67321. }
  67322. return null;
  67323. };
  67324. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67325. for (var i in names) {
  67326. if (mesh.name === names[i]) {
  67327. hierarchyIds.push(mesh.id);
  67328. return true;
  67329. }
  67330. }
  67331. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67332. hierarchyIds.push(mesh.id);
  67333. return true;
  67334. }
  67335. return false;
  67336. };
  67337. var logOperation = function (operation, producer) {
  67338. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67339. };
  67340. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67341. if (addToScene === void 0) { addToScene = false; }
  67342. var container = new BABYLON.AssetContainer(scene);
  67343. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67344. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67345. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67346. // and avoid problems with multiple concurrent .babylon loads.
  67347. var log = "importScene has failed JSON parse";
  67348. try {
  67349. var parsedData = JSON.parse(data);
  67350. log = "";
  67351. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67352. var index;
  67353. var cache;
  67354. // Lights
  67355. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67356. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67357. var parsedLight = parsedData.lights[index];
  67358. var light = BABYLON.Light.Parse(parsedLight, scene);
  67359. if (light) {
  67360. container.lights.push(light);
  67361. log += (index === 0 ? "\n\tLights:" : "");
  67362. log += "\n\t\t" + light.toString(fullDetails);
  67363. }
  67364. }
  67365. }
  67366. // Animations
  67367. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67368. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67369. var parsedAnimation = parsedData.animations[index];
  67370. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67371. scene.animations.push(animation);
  67372. container.animations.push(animation);
  67373. log += (index === 0 ? "\n\tAnimations:" : "");
  67374. log += "\n\t\t" + animation.toString(fullDetails);
  67375. }
  67376. }
  67377. // Materials
  67378. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67379. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67380. var parsedMaterial = parsedData.materials[index];
  67381. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67382. container.materials.push(mat);
  67383. log += (index === 0 ? "\n\tMaterials:" : "");
  67384. log += "\n\t\t" + mat.toString(fullDetails);
  67385. }
  67386. }
  67387. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67388. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67389. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67390. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67391. container.multiMaterials.push(mmat);
  67392. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67393. log += "\n\t\t" + mmat.toString(fullDetails);
  67394. }
  67395. }
  67396. // Morph targets
  67397. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67398. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67399. var managerData = _a[_i];
  67400. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67401. }
  67402. }
  67403. // Skeletons
  67404. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67405. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67406. var parsedSkeleton = parsedData.skeletons[index];
  67407. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67408. container.skeletons.push(skeleton);
  67409. log += (index === 0 ? "\n\tSkeletons:" : "");
  67410. log += "\n\t\t" + skeleton.toString(fullDetails);
  67411. }
  67412. }
  67413. // Geometries
  67414. var geometries = parsedData.geometries;
  67415. if (geometries !== undefined && geometries !== null) {
  67416. var addedGeometry = new Array();
  67417. // Boxes
  67418. var boxes = geometries.boxes;
  67419. if (boxes !== undefined && boxes !== null) {
  67420. for (index = 0, cache = boxes.length; index < cache; index++) {
  67421. var parsedBox = boxes[index];
  67422. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67423. }
  67424. }
  67425. // Spheres
  67426. var spheres = geometries.spheres;
  67427. if (spheres !== undefined && spheres !== null) {
  67428. for (index = 0, cache = spheres.length; index < cache; index++) {
  67429. var parsedSphere = spheres[index];
  67430. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67431. }
  67432. }
  67433. // Cylinders
  67434. var cylinders = geometries.cylinders;
  67435. if (cylinders !== undefined && cylinders !== null) {
  67436. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67437. var parsedCylinder = cylinders[index];
  67438. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67439. }
  67440. }
  67441. // Toruses
  67442. var toruses = geometries.toruses;
  67443. if (toruses !== undefined && toruses !== null) {
  67444. for (index = 0, cache = toruses.length; index < cache; index++) {
  67445. var parsedTorus = toruses[index];
  67446. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67447. }
  67448. }
  67449. // Grounds
  67450. var grounds = geometries.grounds;
  67451. if (grounds !== undefined && grounds !== null) {
  67452. for (index = 0, cache = grounds.length; index < cache; index++) {
  67453. var parsedGround = grounds[index];
  67454. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67455. }
  67456. }
  67457. // Planes
  67458. var planes = geometries.planes;
  67459. if (planes !== undefined && planes !== null) {
  67460. for (index = 0, cache = planes.length; index < cache; index++) {
  67461. var parsedPlane = planes[index];
  67462. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67463. }
  67464. }
  67465. // TorusKnots
  67466. var torusKnots = geometries.torusKnots;
  67467. if (torusKnots !== undefined && torusKnots !== null) {
  67468. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67469. var parsedTorusKnot = torusKnots[index];
  67470. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67471. }
  67472. }
  67473. // VertexData
  67474. var vertexData = geometries.vertexData;
  67475. if (vertexData !== undefined && vertexData !== null) {
  67476. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67477. var parsedVertexData = vertexData[index];
  67478. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67479. }
  67480. }
  67481. addedGeometry.forEach(function (g) {
  67482. if (g) {
  67483. container.geometries.push(g);
  67484. }
  67485. });
  67486. }
  67487. // Transform nodes
  67488. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67489. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67490. var parsedTransformNode = parsedData.transformNodes[index];
  67491. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67492. container.transformNodes.push(node);
  67493. }
  67494. }
  67495. // Meshes
  67496. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67497. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67498. var parsedMesh = parsedData.meshes[index];
  67499. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67500. container.meshes.push(mesh);
  67501. log += (index === 0 ? "\n\tMeshes:" : "");
  67502. log += "\n\t\t" + mesh.toString(fullDetails);
  67503. }
  67504. }
  67505. // Cameras
  67506. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67507. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67508. var parsedCamera = parsedData.cameras[index];
  67509. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67510. container.cameras.push(camera);
  67511. log += (index === 0 ? "\n\tCameras:" : "");
  67512. log += "\n\t\t" + camera.toString(fullDetails);
  67513. }
  67514. }
  67515. // Browsing all the graph to connect the dots
  67516. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67517. var camera = scene.cameras[index];
  67518. if (camera._waitingParentId) {
  67519. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67520. camera._waitingParentId = null;
  67521. }
  67522. }
  67523. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67524. var light_1 = scene.lights[index];
  67525. if (light_1 && light_1._waitingParentId) {
  67526. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67527. light_1._waitingParentId = null;
  67528. }
  67529. }
  67530. // Sounds
  67531. // TODO: add sound
  67532. var loadedSounds = [];
  67533. var loadedSound;
  67534. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67535. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67536. var parsedSound = parsedData.sounds[index];
  67537. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67538. if (!parsedSound.url)
  67539. parsedSound.url = parsedSound.name;
  67540. if (!loadedSounds[parsedSound.url]) {
  67541. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67542. loadedSounds[parsedSound.url] = loadedSound;
  67543. container.sounds.push(loadedSound);
  67544. }
  67545. else {
  67546. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67547. }
  67548. }
  67549. else {
  67550. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67551. }
  67552. }
  67553. }
  67554. loadedSounds = [];
  67555. // Connect parents & children and parse actions
  67556. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67557. var transformNode = scene.transformNodes[index];
  67558. if (transformNode._waitingParentId) {
  67559. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67560. transformNode._waitingParentId = null;
  67561. }
  67562. }
  67563. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67564. var mesh = scene.meshes[index];
  67565. if (mesh._waitingParentId) {
  67566. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67567. mesh._waitingParentId = null;
  67568. }
  67569. if (mesh._waitingActions) {
  67570. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67571. mesh._waitingActions = null;
  67572. }
  67573. }
  67574. // freeze world matrix application
  67575. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67576. var currentMesh = scene.meshes[index];
  67577. if (currentMesh._waitingFreezeWorldMatrix) {
  67578. currentMesh.freezeWorldMatrix();
  67579. currentMesh._waitingFreezeWorldMatrix = null;
  67580. }
  67581. else {
  67582. currentMesh.computeWorldMatrix(true);
  67583. }
  67584. }
  67585. // Particles Systems
  67586. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67587. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67588. var parsedParticleSystem = parsedData.particleSystems[index];
  67589. if (parsedParticleSystem.activeParticleCount) {
  67590. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67591. container.particleSystems.push(ps);
  67592. }
  67593. else {
  67594. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67595. container.particleSystems.push(ps);
  67596. }
  67597. }
  67598. }
  67599. // Lens flares
  67600. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67601. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67602. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67603. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67604. container.lensFlareSystems.push(lf);
  67605. }
  67606. }
  67607. // Shadows
  67608. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67609. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67610. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67611. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67612. container.shadowGenerators.push(sg);
  67613. }
  67614. }
  67615. // Lights exclusions / inclusions
  67616. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67617. var light_2 = scene.lights[index];
  67618. // Excluded check
  67619. if (light_2._excludedMeshesIds.length > 0) {
  67620. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67621. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67622. if (excludedMesh) {
  67623. light_2.excludedMeshes.push(excludedMesh);
  67624. }
  67625. }
  67626. light_2._excludedMeshesIds = [];
  67627. }
  67628. // Included check
  67629. if (light_2._includedOnlyMeshesIds.length > 0) {
  67630. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67631. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67632. if (includedOnlyMesh) {
  67633. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67634. }
  67635. }
  67636. light_2._includedOnlyMeshesIds = [];
  67637. }
  67638. }
  67639. // Effect layers
  67640. if (parsedData.effectLayers) {
  67641. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67642. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67643. container.effectLayers.push(effectLayer);
  67644. }
  67645. }
  67646. // Actions (scene)
  67647. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67648. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67649. }
  67650. if (!addToScene) {
  67651. container.removeAllFromScene();
  67652. }
  67653. }
  67654. catch (err) {
  67655. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67656. if (onError) {
  67657. onError(msg, err);
  67658. }
  67659. else {
  67660. BABYLON.Tools.Log(msg);
  67661. throw err;
  67662. }
  67663. }
  67664. finally {
  67665. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67666. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67667. }
  67668. }
  67669. return container;
  67670. };
  67671. BABYLON.SceneLoader.RegisterPlugin({
  67672. name: "babylon.js",
  67673. extensions: ".babylon",
  67674. canDirectLoad: function (data) {
  67675. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67676. return true;
  67677. }
  67678. return false;
  67679. },
  67680. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67681. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67682. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67683. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67684. // and avoid problems with multiple concurrent .babylon loads.
  67685. var log = "importMesh has failed JSON parse";
  67686. try {
  67687. var parsedData = JSON.parse(data);
  67688. log = "";
  67689. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67690. if (!meshesNames) {
  67691. meshesNames = null;
  67692. }
  67693. else if (!Array.isArray(meshesNames)) {
  67694. meshesNames = [meshesNames];
  67695. }
  67696. var hierarchyIds = new Array();
  67697. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67698. var loadedSkeletonsIds = [];
  67699. var loadedMaterialsIds = [];
  67700. var index;
  67701. var cache;
  67702. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67703. var parsedMesh = parsedData.meshes[index];
  67704. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67705. if (meshesNames !== null) {
  67706. // Remove found mesh name from list.
  67707. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67708. }
  67709. //Geometry?
  67710. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67711. //does the file contain geometries?
  67712. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67713. //find the correct geometry and add it to the scene
  67714. var found = false;
  67715. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67716. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67717. return;
  67718. }
  67719. else {
  67720. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67721. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67722. switch (geometryType) {
  67723. case "boxes":
  67724. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67725. break;
  67726. case "spheres":
  67727. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67728. break;
  67729. case "cylinders":
  67730. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67731. break;
  67732. case "toruses":
  67733. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67734. break;
  67735. case "grounds":
  67736. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67737. break;
  67738. case "planes":
  67739. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67740. break;
  67741. case "torusKnots":
  67742. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67743. break;
  67744. case "vertexData":
  67745. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67746. break;
  67747. }
  67748. found = true;
  67749. }
  67750. });
  67751. }
  67752. });
  67753. if (found === false) {
  67754. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67755. }
  67756. }
  67757. }
  67758. // Material ?
  67759. if (parsedMesh.materialId) {
  67760. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67761. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67762. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67763. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67764. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67765. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67766. var subMatId = parsedMultiMaterial.materials[matIndex];
  67767. loadedMaterialsIds.push(subMatId);
  67768. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67769. if (mat) {
  67770. log += "\n\tMaterial " + mat.toString(fullDetails);
  67771. }
  67772. }
  67773. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67774. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67775. if (mmat) {
  67776. materialFound = true;
  67777. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67778. }
  67779. break;
  67780. }
  67781. }
  67782. }
  67783. if (materialFound === false) {
  67784. loadedMaterialsIds.push(parsedMesh.materialId);
  67785. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67786. if (!mat) {
  67787. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67788. }
  67789. else {
  67790. log += "\n\tMaterial " + mat.toString(fullDetails);
  67791. }
  67792. }
  67793. }
  67794. // Skeleton ?
  67795. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67796. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67797. if (skeletonAlreadyLoaded === false) {
  67798. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67799. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67800. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67801. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67802. skeletons.push(skeleton);
  67803. loadedSkeletonsIds.push(parsedSkeleton.id);
  67804. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67805. }
  67806. }
  67807. }
  67808. }
  67809. // Morph targets ?
  67810. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67811. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67812. var managerData = _a[_i];
  67813. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67814. }
  67815. }
  67816. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67817. meshes.push(mesh);
  67818. log += "\n\tMesh " + mesh.toString(fullDetails);
  67819. }
  67820. }
  67821. // Connecting parents
  67822. var currentMesh;
  67823. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67824. currentMesh = scene.meshes[index];
  67825. if (currentMesh._waitingParentId) {
  67826. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67827. currentMesh._waitingParentId = null;
  67828. }
  67829. }
  67830. // freeze and compute world matrix application
  67831. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67832. currentMesh = scene.meshes[index];
  67833. if (currentMesh._waitingFreezeWorldMatrix) {
  67834. currentMesh.freezeWorldMatrix();
  67835. currentMesh._waitingFreezeWorldMatrix = null;
  67836. }
  67837. else {
  67838. currentMesh.computeWorldMatrix(true);
  67839. }
  67840. }
  67841. }
  67842. // Particles
  67843. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67844. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67845. var parsedParticleSystem = parsedData.particleSystems[index];
  67846. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67847. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67848. }
  67849. }
  67850. }
  67851. return true;
  67852. }
  67853. catch (err) {
  67854. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67855. if (onError) {
  67856. onError(msg, err);
  67857. }
  67858. else {
  67859. BABYLON.Tools.Log(msg);
  67860. throw err;
  67861. }
  67862. }
  67863. finally {
  67864. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67865. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67866. }
  67867. }
  67868. return false;
  67869. },
  67870. load: function (scene, data, rootUrl, onError) {
  67871. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67872. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67873. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67874. // and avoid problems with multiple concurrent .babylon loads.
  67875. var log = "importScene has failed JSON parse";
  67876. try {
  67877. var parsedData = JSON.parse(data);
  67878. log = "";
  67879. // Scene
  67880. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67881. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67882. }
  67883. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67884. scene.autoClear = parsedData.autoClear;
  67885. }
  67886. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67887. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67888. }
  67889. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67890. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67891. }
  67892. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67893. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67894. }
  67895. // Fog
  67896. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67897. scene.fogMode = parsedData.fogMode;
  67898. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67899. scene.fogStart = parsedData.fogStart;
  67900. scene.fogEnd = parsedData.fogEnd;
  67901. scene.fogDensity = parsedData.fogDensity;
  67902. log += "\tFog mode for scene: ";
  67903. switch (scene.fogMode) {
  67904. // getters not compiling, so using hardcoded
  67905. case 1:
  67906. log += "exp\n";
  67907. break;
  67908. case 2:
  67909. log += "exp2\n";
  67910. break;
  67911. case 3:
  67912. log += "linear\n";
  67913. break;
  67914. }
  67915. }
  67916. //Physics
  67917. if (parsedData.physicsEnabled) {
  67918. var physicsPlugin;
  67919. if (parsedData.physicsEngine === "cannon") {
  67920. physicsPlugin = new BABYLON.CannonJSPlugin();
  67921. }
  67922. else if (parsedData.physicsEngine === "oimo") {
  67923. physicsPlugin = new BABYLON.OimoJSPlugin();
  67924. }
  67925. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67926. //else - default engine, which is currently oimo
  67927. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67928. scene.enablePhysics(physicsGravity, physicsPlugin);
  67929. }
  67930. // Metadata
  67931. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67932. scene.metadata = parsedData.metadata;
  67933. }
  67934. //collisions, if defined. otherwise, default is true
  67935. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67936. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67937. }
  67938. scene.workerCollisions = !!parsedData.workerCollisions;
  67939. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67940. if (!container) {
  67941. return false;
  67942. }
  67943. if (parsedData.autoAnimate) {
  67944. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67945. }
  67946. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67947. scene.setActiveCameraByID(parsedData.activeCameraID);
  67948. }
  67949. // Environment texture
  67950. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67951. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67952. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67953. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67954. if (parsedData.environmentTextureRotationY) {
  67955. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67956. }
  67957. scene.environmentTexture = hdrTexture;
  67958. }
  67959. else {
  67960. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67961. if (parsedData.environmentTextureRotationY) {
  67962. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67963. }
  67964. scene.environmentTexture = cubeTexture;
  67965. }
  67966. if (parsedData.createDefaultSkybox === true) {
  67967. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67968. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67969. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67970. }
  67971. }
  67972. // Finish
  67973. return true;
  67974. }
  67975. catch (err) {
  67976. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67977. if (onError) {
  67978. onError(msg, err);
  67979. }
  67980. else {
  67981. BABYLON.Tools.Log(msg);
  67982. throw err;
  67983. }
  67984. }
  67985. finally {
  67986. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67987. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67988. }
  67989. }
  67990. return false;
  67991. },
  67992. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67993. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67994. return container;
  67995. }
  67996. });
  67997. })(BABYLON || (BABYLON = {}));
  67998. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67999. var BABYLON;
  68000. (function (BABYLON) {
  68001. var FilesInput = /** @class */ (function () {
  68002. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68003. this.onProcessFileCallback = function () { return true; };
  68004. this._engine = engine;
  68005. this._currentScene = scene;
  68006. this._sceneLoadedCallback = sceneLoadedCallback;
  68007. this._progressCallback = progressCallback;
  68008. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68009. this._textureLoadingCallback = textureLoadingCallback;
  68010. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68011. this._onReloadCallback = onReloadCallback;
  68012. this._errorCallback = errorCallback;
  68013. }
  68014. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68015. var _this = this;
  68016. if (elementToMonitor) {
  68017. this._elementToMonitor = elementToMonitor;
  68018. this._dragEnterHandler = function (e) { _this.drag(e); };
  68019. this._dragOverHandler = function (e) { _this.drag(e); };
  68020. this._dropHandler = function (e) { _this.drop(e); };
  68021. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68022. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68023. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68024. }
  68025. };
  68026. FilesInput.prototype.dispose = function () {
  68027. if (!this._elementToMonitor) {
  68028. return;
  68029. }
  68030. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68031. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68032. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68033. };
  68034. FilesInput.prototype.renderFunction = function () {
  68035. if (this._additionalRenderLoopLogicCallback) {
  68036. this._additionalRenderLoopLogicCallback();
  68037. }
  68038. if (this._currentScene) {
  68039. if (this._textureLoadingCallback) {
  68040. var remaining = this._currentScene.getWaitingItemsCount();
  68041. if (remaining > 0) {
  68042. this._textureLoadingCallback(remaining);
  68043. }
  68044. }
  68045. this._currentScene.render();
  68046. }
  68047. };
  68048. FilesInput.prototype.drag = function (e) {
  68049. e.stopPropagation();
  68050. e.preventDefault();
  68051. };
  68052. FilesInput.prototype.drop = function (eventDrop) {
  68053. eventDrop.stopPropagation();
  68054. eventDrop.preventDefault();
  68055. this.loadFiles(eventDrop);
  68056. };
  68057. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68058. var _this = this;
  68059. var reader = folder.createReader();
  68060. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68061. reader.readEntries(function (entries) {
  68062. remaining.count += entries.length;
  68063. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68064. var entry = entries_1[_i];
  68065. if (entry.isFile) {
  68066. entry.file(function (file) {
  68067. file.correctName = relativePath + file.name;
  68068. files.push(file);
  68069. if (--remaining.count === 0) {
  68070. callback();
  68071. }
  68072. });
  68073. }
  68074. else if (entry.isDirectory) {
  68075. _this._traverseFolder(entry, files, remaining, callback);
  68076. }
  68077. }
  68078. if (--remaining.count) {
  68079. callback();
  68080. }
  68081. });
  68082. };
  68083. FilesInput.prototype._processFiles = function (files) {
  68084. for (var i = 0; i < files.length; i++) {
  68085. var name = files[i].correctName.toLowerCase();
  68086. var extension = name.split('.').pop();
  68087. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68088. continue;
  68089. }
  68090. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68091. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68092. this._sceneFileToLoad = files[i];
  68093. }
  68094. else {
  68095. FilesInput.FilesToLoad[name] = files[i];
  68096. }
  68097. }
  68098. };
  68099. FilesInput.prototype.loadFiles = function (event) {
  68100. var _this = this;
  68101. if (this._startingProcessingFilesCallback)
  68102. this._startingProcessingFilesCallback();
  68103. // Handling data transfer via drag'n'drop
  68104. if (event && event.dataTransfer && event.dataTransfer.files) {
  68105. this._filesToLoad = event.dataTransfer.files;
  68106. }
  68107. // Handling files from input files
  68108. if (event && event.target && event.target.files) {
  68109. this._filesToLoad = event.target.files;
  68110. }
  68111. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68112. var files_1 = new Array();
  68113. var folders = [];
  68114. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68115. for (var i = 0; i < this._filesToLoad.length; i++) {
  68116. var fileToLoad = this._filesToLoad[i];
  68117. var name_1 = fileToLoad.name.toLowerCase();
  68118. var entry = void 0;
  68119. fileToLoad.correctName = name_1;
  68120. if (items) {
  68121. var item = items[i];
  68122. if (item.getAsEntry) {
  68123. entry = item.getAsEntry();
  68124. }
  68125. else if (item.webkitGetAsEntry) {
  68126. entry = item.webkitGetAsEntry();
  68127. }
  68128. }
  68129. if (!entry) {
  68130. files_1.push(fileToLoad);
  68131. }
  68132. else {
  68133. if (entry.isDirectory) {
  68134. folders.push(entry);
  68135. }
  68136. else {
  68137. files_1.push(fileToLoad);
  68138. }
  68139. }
  68140. }
  68141. if (folders.length === 0) {
  68142. this._processFiles(files_1);
  68143. this._processReload();
  68144. }
  68145. else {
  68146. var remaining = { count: folders.length };
  68147. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68148. var folder = folders_1[_i];
  68149. this._traverseFolder(folder, files_1, remaining, function () {
  68150. _this._processFiles(files_1);
  68151. if (remaining.count === 0) {
  68152. _this._processReload();
  68153. }
  68154. });
  68155. }
  68156. }
  68157. }
  68158. };
  68159. FilesInput.prototype._processReload = function () {
  68160. if (this._onReloadCallback) {
  68161. this._onReloadCallback(this._sceneFileToLoad);
  68162. }
  68163. else {
  68164. this.reload();
  68165. }
  68166. };
  68167. FilesInput.prototype.reload = function () {
  68168. var _this = this;
  68169. // If a scene file has been provided
  68170. if (this._sceneFileToLoad) {
  68171. if (this._currentScene) {
  68172. if (BABYLON.Tools.errorsCount > 0) {
  68173. BABYLON.Tools.ClearLogCache();
  68174. }
  68175. this._engine.stopRenderLoop();
  68176. this._currentScene.dispose();
  68177. }
  68178. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68179. if (_this._progressCallback) {
  68180. _this._progressCallback(progress);
  68181. }
  68182. }).then(function (scene) {
  68183. _this._currentScene = scene;
  68184. if (_this._sceneLoadedCallback) {
  68185. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68186. }
  68187. // Wait for textures and shaders to be ready
  68188. _this._currentScene.executeWhenReady(function () {
  68189. _this._engine.runRenderLoop(function () {
  68190. _this.renderFunction();
  68191. });
  68192. });
  68193. }).catch(function (error) {
  68194. if (_this._errorCallback) {
  68195. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68196. }
  68197. });
  68198. }
  68199. else {
  68200. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68201. }
  68202. };
  68203. FilesInput.FilesToLoad = {};
  68204. return FilesInput;
  68205. }());
  68206. BABYLON.FilesInput = FilesInput;
  68207. })(BABYLON || (BABYLON = {}));
  68208. //# sourceMappingURL=babylon.filesInput.js.map
  68209. var BABYLON;
  68210. (function (BABYLON) {
  68211. /**
  68212. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68213. * The underlying implementation relies on an associative array to ensure the best performances.
  68214. * The value can be anything including 'null' but except 'undefined'
  68215. */
  68216. var StringDictionary = /** @class */ (function () {
  68217. function StringDictionary() {
  68218. this._count = 0;
  68219. this._data = {};
  68220. }
  68221. /**
  68222. * This will clear this dictionary and copy the content from the 'source' one.
  68223. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68224. * @param source the dictionary to take the content from and copy to this dictionary
  68225. */
  68226. StringDictionary.prototype.copyFrom = function (source) {
  68227. var _this = this;
  68228. this.clear();
  68229. source.forEach(function (t, v) { return _this.add(t, v); });
  68230. };
  68231. /**
  68232. * Get a value based from its key
  68233. * @param key the given key to get the matching value from
  68234. * @return the value if found, otherwise undefined is returned
  68235. */
  68236. StringDictionary.prototype.get = function (key) {
  68237. var val = this._data[key];
  68238. if (val !== undefined) {
  68239. return val;
  68240. }
  68241. return undefined;
  68242. };
  68243. /**
  68244. * Get a value from its key or add it if it doesn't exist.
  68245. * This method will ensure you that a given key/data will be present in the dictionary.
  68246. * @param key the given key to get the matching value from
  68247. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68248. * The factory will only be invoked if there's no data for the given key.
  68249. * @return the value corresponding to the key.
  68250. */
  68251. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68252. var val = this.get(key);
  68253. if (val !== undefined) {
  68254. return val;
  68255. }
  68256. val = factory(key);
  68257. if (val) {
  68258. this.add(key, val);
  68259. }
  68260. return val;
  68261. };
  68262. /**
  68263. * Get a value from its key if present in the dictionary otherwise add it
  68264. * @param key the key to get the value from
  68265. * @param val if there's no such key/value pair in the dictionary add it with this value
  68266. * @return the value corresponding to the key
  68267. */
  68268. StringDictionary.prototype.getOrAdd = function (key, val) {
  68269. var curVal = this.get(key);
  68270. if (curVal !== undefined) {
  68271. return curVal;
  68272. }
  68273. this.add(key, val);
  68274. return val;
  68275. };
  68276. /**
  68277. * Check if there's a given key in the dictionary
  68278. * @param key the key to check for
  68279. * @return true if the key is present, false otherwise
  68280. */
  68281. StringDictionary.prototype.contains = function (key) {
  68282. return this._data[key] !== undefined;
  68283. };
  68284. /**
  68285. * Add a new key and its corresponding value
  68286. * @param key the key to add
  68287. * @param value the value corresponding to the key
  68288. * @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
  68289. */
  68290. StringDictionary.prototype.add = function (key, value) {
  68291. if (this._data[key] !== undefined) {
  68292. return false;
  68293. }
  68294. this._data[key] = value;
  68295. ++this._count;
  68296. return true;
  68297. };
  68298. StringDictionary.prototype.set = function (key, value) {
  68299. if (this._data[key] === undefined) {
  68300. return false;
  68301. }
  68302. this._data[key] = value;
  68303. return true;
  68304. };
  68305. /**
  68306. * Get the element of the given key and remove it from the dictionary
  68307. * @param key
  68308. */
  68309. StringDictionary.prototype.getAndRemove = function (key) {
  68310. var val = this.get(key);
  68311. if (val !== undefined) {
  68312. delete this._data[key];
  68313. --this._count;
  68314. return val;
  68315. }
  68316. return null;
  68317. };
  68318. /**
  68319. * Remove a key/value from the dictionary.
  68320. * @param key the key to remove
  68321. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68322. */
  68323. StringDictionary.prototype.remove = function (key) {
  68324. if (this.contains(key)) {
  68325. delete this._data[key];
  68326. --this._count;
  68327. return true;
  68328. }
  68329. return false;
  68330. };
  68331. /**
  68332. * Clear the whole content of the dictionary
  68333. */
  68334. StringDictionary.prototype.clear = function () {
  68335. this._data = {};
  68336. this._count = 0;
  68337. };
  68338. Object.defineProperty(StringDictionary.prototype, "count", {
  68339. get: function () {
  68340. return this._count;
  68341. },
  68342. enumerable: true,
  68343. configurable: true
  68344. });
  68345. /**
  68346. * Execute a callback on each key/val of the dictionary.
  68347. * Note that you can remove any element in this dictionary in the callback implementation
  68348. * @param callback the callback to execute on a given key/value pair
  68349. */
  68350. StringDictionary.prototype.forEach = function (callback) {
  68351. for (var cur in this._data) {
  68352. var val = this._data[cur];
  68353. callback(cur, val);
  68354. }
  68355. };
  68356. /**
  68357. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68358. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68359. * Note that you can remove any element in this dictionary in the callback implementation
  68360. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68361. */
  68362. StringDictionary.prototype.first = function (callback) {
  68363. for (var cur in this._data) {
  68364. var val = this._data[cur];
  68365. var res = callback(cur, val);
  68366. if (res) {
  68367. return res;
  68368. }
  68369. }
  68370. return null;
  68371. };
  68372. return StringDictionary;
  68373. }());
  68374. BABYLON.StringDictionary = StringDictionary;
  68375. })(BABYLON || (BABYLON = {}));
  68376. //# sourceMappingURL=babylon.stringDictionary.js.map
  68377. var BABYLON;
  68378. (function (BABYLON) {
  68379. var Tags = /** @class */ (function () {
  68380. function Tags() {
  68381. }
  68382. Tags.EnableFor = function (obj) {
  68383. obj._tags = obj._tags || {};
  68384. obj.hasTags = function () {
  68385. return Tags.HasTags(obj);
  68386. };
  68387. obj.addTags = function (tagsString) {
  68388. return Tags.AddTagsTo(obj, tagsString);
  68389. };
  68390. obj.removeTags = function (tagsString) {
  68391. return Tags.RemoveTagsFrom(obj, tagsString);
  68392. };
  68393. obj.matchesTagsQuery = function (tagsQuery) {
  68394. return Tags.MatchesQuery(obj, tagsQuery);
  68395. };
  68396. };
  68397. Tags.DisableFor = function (obj) {
  68398. delete obj._tags;
  68399. delete obj.hasTags;
  68400. delete obj.addTags;
  68401. delete obj.removeTags;
  68402. delete obj.matchesTagsQuery;
  68403. };
  68404. Tags.HasTags = function (obj) {
  68405. if (!obj._tags) {
  68406. return false;
  68407. }
  68408. return !BABYLON.Tools.IsEmpty(obj._tags);
  68409. };
  68410. Tags.GetTags = function (obj, asString) {
  68411. if (asString === void 0) { asString = true; }
  68412. if (!obj._tags) {
  68413. return null;
  68414. }
  68415. if (asString) {
  68416. var tagsArray = [];
  68417. for (var tag in obj._tags) {
  68418. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68419. tagsArray.push(tag);
  68420. }
  68421. }
  68422. return tagsArray.join(" ");
  68423. }
  68424. else {
  68425. return obj._tags;
  68426. }
  68427. };
  68428. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68429. // a tag cannot start with '||', '&&', and '!'
  68430. // it cannot contain whitespaces
  68431. Tags.AddTagsTo = function (obj, tagsString) {
  68432. if (!tagsString) {
  68433. return;
  68434. }
  68435. if (typeof tagsString !== "string") {
  68436. return;
  68437. }
  68438. var tags = tagsString.split(" ");
  68439. tags.forEach(function (tag, index, array) {
  68440. Tags._AddTagTo(obj, tag);
  68441. });
  68442. };
  68443. Tags._AddTagTo = function (obj, tag) {
  68444. tag = tag.trim();
  68445. if (tag === "" || tag === "true" || tag === "false") {
  68446. return;
  68447. }
  68448. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68449. return;
  68450. }
  68451. Tags.EnableFor(obj);
  68452. obj._tags[tag] = true;
  68453. };
  68454. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68455. if (!Tags.HasTags(obj)) {
  68456. return;
  68457. }
  68458. var tags = tagsString.split(" ");
  68459. for (var t in tags) {
  68460. Tags._RemoveTagFrom(obj, tags[t]);
  68461. }
  68462. };
  68463. Tags._RemoveTagFrom = function (obj, tag) {
  68464. delete obj._tags[tag];
  68465. };
  68466. Tags.MatchesQuery = function (obj, tagsQuery) {
  68467. if (tagsQuery === undefined) {
  68468. return true;
  68469. }
  68470. if (tagsQuery === "") {
  68471. return Tags.HasTags(obj);
  68472. }
  68473. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68474. };
  68475. return Tags;
  68476. }());
  68477. BABYLON.Tags = Tags;
  68478. })(BABYLON || (BABYLON = {}));
  68479. //# sourceMappingURL=babylon.tags.js.map
  68480. var BABYLON;
  68481. (function (BABYLON) {
  68482. /**
  68483. * Class used to evalaute queries containing `and` and `or` operators
  68484. */
  68485. var AndOrNotEvaluator = /** @class */ (function () {
  68486. function AndOrNotEvaluator() {
  68487. }
  68488. /**
  68489. * Evaluate a query
  68490. * @param query defines the query to evaluate
  68491. * @param evaluateCallback defines the callback used to filter result
  68492. * @returns true if the query matches
  68493. */
  68494. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68495. if (!query.match(/\([^\(\)]*\)/g)) {
  68496. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68497. }
  68498. else {
  68499. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68500. // remove parenthesis
  68501. r = r.slice(1, r.length - 1);
  68502. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68503. });
  68504. }
  68505. if (query === "true") {
  68506. return true;
  68507. }
  68508. if (query === "false") {
  68509. return false;
  68510. }
  68511. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68512. };
  68513. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68514. evaluateCallback = evaluateCallback || (function (r) {
  68515. return r === "true" ? true : false;
  68516. });
  68517. var result;
  68518. var or = parenthesisContent.split("||");
  68519. for (var i in or) {
  68520. if (or.hasOwnProperty(i)) {
  68521. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68522. var and = ori.split("&&");
  68523. if (and.length > 1) {
  68524. for (var j = 0; j < and.length; ++j) {
  68525. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68526. if (andj !== "true" && andj !== "false") {
  68527. if (andj[0] === "!") {
  68528. result = !evaluateCallback(andj.substring(1));
  68529. }
  68530. else {
  68531. result = evaluateCallback(andj);
  68532. }
  68533. }
  68534. else {
  68535. result = andj === "true" ? true : false;
  68536. }
  68537. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68538. ori = "false";
  68539. break;
  68540. }
  68541. }
  68542. }
  68543. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68544. result = true;
  68545. break;
  68546. }
  68547. // result equals false (or undefined)
  68548. if (ori !== "true" && ori !== "false") {
  68549. if (ori[0] === "!") {
  68550. result = !evaluateCallback(ori.substring(1));
  68551. }
  68552. else {
  68553. result = evaluateCallback(ori);
  68554. }
  68555. }
  68556. else {
  68557. result = ori === "true" ? true : false;
  68558. }
  68559. }
  68560. }
  68561. // the whole parenthesis scope is replaced by 'true' or 'false'
  68562. return result ? "true" : "false";
  68563. };
  68564. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68565. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68566. // remove whitespaces
  68567. r = r.replace(/[\s]/g, function () { return ""; });
  68568. return r.length % 2 ? "!" : "";
  68569. });
  68570. booleanString = booleanString.trim();
  68571. if (booleanString === "!true") {
  68572. booleanString = "false";
  68573. }
  68574. else if (booleanString === "!false") {
  68575. booleanString = "true";
  68576. }
  68577. return booleanString;
  68578. };
  68579. return AndOrNotEvaluator;
  68580. }());
  68581. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68582. })(BABYLON || (BABYLON = {}));
  68583. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68584. var BABYLON;
  68585. (function (BABYLON) {
  68586. /**
  68587. * Class used to enable access to IndexedDB
  68588. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68589. */
  68590. var Database = /** @class */ (function () {
  68591. /**
  68592. * Creates a new Database
  68593. * @param urlToScene defines the url to load the scene
  68594. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68595. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68596. */
  68597. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68598. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68599. var _this = this;
  68600. // Handling various flavors of prefixed version of IndexedDB
  68601. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68602. this.callbackManifestChecked = callbackManifestChecked;
  68603. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68604. this.db = null;
  68605. this._enableSceneOffline = false;
  68606. this._enableTexturesOffline = false;
  68607. this.manifestVersionFound = 0;
  68608. this.mustUpdateRessources = false;
  68609. this.hasReachedQuota = false;
  68610. if (!Database.IDBStorageEnabled) {
  68611. this.callbackManifestChecked(true);
  68612. }
  68613. else {
  68614. if (disableManifestCheck) {
  68615. this._enableSceneOffline = true;
  68616. this._enableTexturesOffline = true;
  68617. this.manifestVersionFound = 1;
  68618. BABYLON.Tools.SetImmediate(function () {
  68619. _this.callbackManifestChecked(true);
  68620. });
  68621. }
  68622. else {
  68623. this._checkManifestFile();
  68624. }
  68625. }
  68626. }
  68627. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68628. /**
  68629. * Gets a boolean indicating if scene must be saved in the database
  68630. */
  68631. get: function () {
  68632. return this._enableSceneOffline;
  68633. },
  68634. enumerable: true,
  68635. configurable: true
  68636. });
  68637. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68638. /**
  68639. * Gets a boolean indicating if textures must be saved in the database
  68640. */
  68641. get: function () {
  68642. return this._enableTexturesOffline;
  68643. },
  68644. enumerable: true,
  68645. configurable: true
  68646. });
  68647. Database.prototype._checkManifestFile = function () {
  68648. var _this = this;
  68649. var noManifestFile = function () {
  68650. _this._enableSceneOffline = false;
  68651. _this._enableTexturesOffline = false;
  68652. _this.callbackManifestChecked(false);
  68653. };
  68654. var timeStampUsed = false;
  68655. var manifestURL = this.currentSceneUrl + ".manifest";
  68656. var xhr = new XMLHttpRequest();
  68657. if (navigator.onLine) {
  68658. // Adding a timestamp to by-pass browsers' cache
  68659. timeStampUsed = true;
  68660. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68661. }
  68662. xhr.open("GET", manifestURL, true);
  68663. xhr.addEventListener("load", function () {
  68664. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68665. try {
  68666. var manifestFile = JSON.parse(xhr.response);
  68667. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68668. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68669. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68670. _this.manifestVersionFound = manifestFile.version;
  68671. }
  68672. if (_this.callbackManifestChecked) {
  68673. _this.callbackManifestChecked(true);
  68674. }
  68675. }
  68676. catch (ex) {
  68677. noManifestFile();
  68678. }
  68679. }
  68680. else {
  68681. noManifestFile();
  68682. }
  68683. }, false);
  68684. xhr.addEventListener("error", function (event) {
  68685. if (timeStampUsed) {
  68686. timeStampUsed = false;
  68687. // Let's retry without the timeStamp
  68688. // It could fail when coupled with HTML5 Offline API
  68689. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68690. xhr.open("GET", retryManifestURL, true);
  68691. xhr.send();
  68692. }
  68693. else {
  68694. noManifestFile();
  68695. }
  68696. }, false);
  68697. try {
  68698. xhr.send();
  68699. }
  68700. catch (ex) {
  68701. BABYLON.Tools.Error("Error on XHR send request.");
  68702. this.callbackManifestChecked(false);
  68703. }
  68704. };
  68705. /**
  68706. * Open the database and make it available
  68707. * @param successCallback defines the callback to call on success
  68708. * @param errorCallback defines the callback to call on error
  68709. */
  68710. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68711. var _this = this;
  68712. var handleError = function () {
  68713. _this.isSupported = false;
  68714. if (errorCallback)
  68715. errorCallback();
  68716. };
  68717. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68718. // Your browser doesn't support IndexedDB
  68719. this.isSupported = false;
  68720. if (errorCallback)
  68721. errorCallback();
  68722. }
  68723. else {
  68724. // If the DB hasn't been opened or created yet
  68725. if (!this.db) {
  68726. this.hasReachedQuota = false;
  68727. this.isSupported = true;
  68728. var request = this.idbFactory.open("babylonjs", 1);
  68729. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68730. request.onerror = function (event) {
  68731. handleError();
  68732. };
  68733. // executes when a version change transaction cannot complete due to other active transactions
  68734. request.onblocked = function (event) {
  68735. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68736. handleError();
  68737. };
  68738. // DB has been opened successfully
  68739. request.onsuccess = function (event) {
  68740. _this.db = request.result;
  68741. successCallback();
  68742. };
  68743. // Initialization of the DB. Creating Scenes & Textures stores
  68744. request.onupgradeneeded = function (event) {
  68745. _this.db = (event.target).result;
  68746. if (_this.db) {
  68747. try {
  68748. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68749. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68750. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68751. }
  68752. catch (ex) {
  68753. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68754. handleError();
  68755. }
  68756. }
  68757. };
  68758. }
  68759. // DB has already been created and opened
  68760. else {
  68761. if (successCallback)
  68762. successCallback();
  68763. }
  68764. }
  68765. };
  68766. /**
  68767. * Loads an image from the database
  68768. * @param url defines the url to load from
  68769. * @param image defines the target DOM image
  68770. */
  68771. Database.prototype.loadImageFromDB = function (url, image) {
  68772. var _this = this;
  68773. var completeURL = Database._ReturnFullUrlLocation(url);
  68774. var saveAndLoadImage = function () {
  68775. if (!_this.hasReachedQuota && _this.db !== null) {
  68776. // the texture is not yet in the DB, let's try to save it
  68777. _this._saveImageIntoDBAsync(completeURL, image);
  68778. }
  68779. // If the texture is not in the DB and we've reached the DB quota limit
  68780. // let's load it directly from the web
  68781. else {
  68782. image.src = url;
  68783. }
  68784. };
  68785. if (!this.mustUpdateRessources) {
  68786. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68787. }
  68788. // First time we're download the images or update requested in the manifest file by a version change
  68789. else {
  68790. saveAndLoadImage();
  68791. }
  68792. };
  68793. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68794. if (this.isSupported && this.db !== null) {
  68795. var texture;
  68796. var transaction = this.db.transaction(["textures"]);
  68797. transaction.onabort = function (event) {
  68798. image.src = url;
  68799. };
  68800. transaction.oncomplete = function (event) {
  68801. var blobTextureURL;
  68802. if (texture) {
  68803. var URL = window.URL || window.webkitURL;
  68804. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68805. image.onerror = function () {
  68806. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68807. image.src = url;
  68808. };
  68809. image.src = blobTextureURL;
  68810. }
  68811. else {
  68812. notInDBCallback();
  68813. }
  68814. };
  68815. var getRequest = transaction.objectStore("textures").get(url);
  68816. getRequest.onsuccess = function (event) {
  68817. texture = (event.target).result;
  68818. };
  68819. getRequest.onerror = function (event) {
  68820. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68821. image.src = url;
  68822. };
  68823. }
  68824. else {
  68825. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68826. image.src = url;
  68827. }
  68828. };
  68829. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68830. var _this = this;
  68831. if (this.isSupported) {
  68832. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68833. var generateBlobUrl = function () {
  68834. var blobTextureURL;
  68835. if (blob) {
  68836. var URL = window.URL || window.webkitURL;
  68837. try {
  68838. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68839. }
  68840. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68841. catch (ex) {
  68842. blobTextureURL = URL.createObjectURL(blob);
  68843. }
  68844. }
  68845. if (blobTextureURL) {
  68846. image.src = blobTextureURL;
  68847. }
  68848. };
  68849. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68850. var xhr = new XMLHttpRequest(), blob;
  68851. xhr.open("GET", url, true);
  68852. xhr.responseType = "blob";
  68853. xhr.addEventListener("load", function () {
  68854. if (xhr.status === 200 && _this.db) {
  68855. // Blob as response (XHR2)
  68856. blob = xhr.response;
  68857. var transaction = _this.db.transaction(["textures"], "readwrite");
  68858. // the transaction could abort because of a QuotaExceededError error
  68859. transaction.onabort = function (event) {
  68860. try {
  68861. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68862. var srcElement = (event.srcElement || event.target);
  68863. var error = srcElement.error;
  68864. if (error && error.name === "QuotaExceededError") {
  68865. _this.hasReachedQuota = true;
  68866. }
  68867. }
  68868. catch (ex) { }
  68869. generateBlobUrl();
  68870. };
  68871. transaction.oncomplete = function (event) {
  68872. generateBlobUrl();
  68873. };
  68874. var newTexture = { textureUrl: url, data: blob };
  68875. try {
  68876. // Put the blob into the dabase
  68877. var addRequest = transaction.objectStore("textures").put(newTexture);
  68878. addRequest.onsuccess = function (event) {
  68879. };
  68880. addRequest.onerror = function (event) {
  68881. generateBlobUrl();
  68882. };
  68883. }
  68884. catch (ex) {
  68885. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68886. if (ex.code === 25) {
  68887. Database.IsUASupportingBlobStorage = false;
  68888. }
  68889. image.src = url;
  68890. }
  68891. }
  68892. else {
  68893. image.src = url;
  68894. }
  68895. }, false);
  68896. xhr.addEventListener("error", function (event) {
  68897. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68898. image.src = url;
  68899. }, false);
  68900. xhr.send();
  68901. }
  68902. else {
  68903. image.src = url;
  68904. }
  68905. }
  68906. else {
  68907. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68908. image.src = url;
  68909. }
  68910. };
  68911. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68912. var _this = this;
  68913. var updateVersion = function () {
  68914. // the version is not yet in the DB or we need to update it
  68915. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68916. };
  68917. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68918. };
  68919. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68920. var _this = this;
  68921. if (this.isSupported && this.db) {
  68922. var version;
  68923. try {
  68924. var transaction = this.db.transaction(["versions"]);
  68925. transaction.oncomplete = function (event) {
  68926. if (version) {
  68927. // If the version in the JSON file is different from the version in DB
  68928. if (_this.manifestVersionFound !== version.data) {
  68929. _this.mustUpdateRessources = true;
  68930. updateInDBCallback();
  68931. }
  68932. else {
  68933. callback(version.data);
  68934. }
  68935. }
  68936. // version was not found in DB
  68937. else {
  68938. _this.mustUpdateRessources = true;
  68939. updateInDBCallback();
  68940. }
  68941. };
  68942. transaction.onabort = function (event) {
  68943. callback(-1);
  68944. };
  68945. var getRequest = transaction.objectStore("versions").get(url);
  68946. getRequest.onsuccess = function (event) {
  68947. version = (event.target).result;
  68948. };
  68949. getRequest.onerror = function (event) {
  68950. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68951. callback(-1);
  68952. };
  68953. }
  68954. catch (ex) {
  68955. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68956. callback(-1);
  68957. }
  68958. }
  68959. else {
  68960. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68961. callback(-1);
  68962. }
  68963. };
  68964. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68965. var _this = this;
  68966. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68967. try {
  68968. // Open a transaction to the database
  68969. var transaction = this.db.transaction(["versions"], "readwrite");
  68970. // the transaction could abort because of a QuotaExceededError error
  68971. transaction.onabort = function (event) {
  68972. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68973. var error = event.srcElement['error'];
  68974. if (error && error.name === "QuotaExceededError") {
  68975. _this.hasReachedQuota = true;
  68976. }
  68977. }
  68978. catch (ex) { }
  68979. callback(-1);
  68980. };
  68981. transaction.oncomplete = function (event) {
  68982. callback(_this.manifestVersionFound);
  68983. };
  68984. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68985. // Put the scene into the database
  68986. var addRequest = transaction.objectStore("versions").put(newVersion);
  68987. addRequest.onsuccess = function (event) {
  68988. };
  68989. addRequest.onerror = function (event) {
  68990. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68991. };
  68992. }
  68993. catch (ex) {
  68994. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68995. callback(-1);
  68996. }
  68997. }
  68998. else {
  68999. callback(-1);
  69000. }
  69001. };
  69002. /**
  69003. * Loads a file from database
  69004. * @param url defines the URL to load from
  69005. * @param sceneLoaded defines a callback to call on success
  69006. * @param progressCallBack defines a callback to call when progress changed
  69007. * @param errorCallback defines a callback to call on error
  69008. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69009. */
  69010. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69011. var _this = this;
  69012. var completeUrl = Database._ReturnFullUrlLocation(url);
  69013. var saveAndLoadFile = function () {
  69014. // the scene is not yet in the DB, let's try to save it
  69015. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69016. };
  69017. this._checkVersionFromDB(completeUrl, function (version) {
  69018. if (version !== -1) {
  69019. if (!_this.mustUpdateRessources) {
  69020. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69021. }
  69022. else {
  69023. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69024. }
  69025. }
  69026. else {
  69027. if (errorCallback) {
  69028. errorCallback();
  69029. }
  69030. }
  69031. });
  69032. };
  69033. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69034. if (this.isSupported && this.db) {
  69035. var targetStore;
  69036. if (url.indexOf(".babylon") !== -1) {
  69037. targetStore = "scenes";
  69038. }
  69039. else {
  69040. targetStore = "textures";
  69041. }
  69042. var file;
  69043. var transaction = this.db.transaction([targetStore]);
  69044. transaction.oncomplete = function (event) {
  69045. if (file) {
  69046. callback(file.data);
  69047. }
  69048. // file was not found in DB
  69049. else {
  69050. notInDBCallback();
  69051. }
  69052. };
  69053. transaction.onabort = function (event) {
  69054. notInDBCallback();
  69055. };
  69056. var getRequest = transaction.objectStore(targetStore).get(url);
  69057. getRequest.onsuccess = function (event) {
  69058. file = (event.target).result;
  69059. };
  69060. getRequest.onerror = function (event) {
  69061. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69062. notInDBCallback();
  69063. };
  69064. }
  69065. else {
  69066. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69067. callback();
  69068. }
  69069. };
  69070. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69071. var _this = this;
  69072. if (this.isSupported) {
  69073. var targetStore;
  69074. if (url.indexOf(".babylon") !== -1) {
  69075. targetStore = "scenes";
  69076. }
  69077. else {
  69078. targetStore = "textures";
  69079. }
  69080. // Create XHR
  69081. var xhr = new XMLHttpRequest();
  69082. var fileData;
  69083. xhr.open("GET", url, true);
  69084. if (useArrayBuffer) {
  69085. xhr.responseType = "arraybuffer";
  69086. }
  69087. if (progressCallback) {
  69088. xhr.onprogress = progressCallback;
  69089. }
  69090. xhr.addEventListener("load", function () {
  69091. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69092. // Blob as response (XHR2)
  69093. //fileData = xhr.responseText;
  69094. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69095. if (!_this.hasReachedQuota && _this.db) {
  69096. // Open a transaction to the database
  69097. var transaction = _this.db.transaction([targetStore], "readwrite");
  69098. // the transaction could abort because of a QuotaExceededError error
  69099. transaction.onabort = function (event) {
  69100. try {
  69101. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69102. var error = event.srcElement['error'];
  69103. if (error && error.name === "QuotaExceededError") {
  69104. _this.hasReachedQuota = true;
  69105. }
  69106. }
  69107. catch (ex) { }
  69108. callback(fileData);
  69109. };
  69110. transaction.oncomplete = function (event) {
  69111. callback(fileData);
  69112. };
  69113. var newFile;
  69114. if (targetStore === "scenes") {
  69115. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69116. }
  69117. else {
  69118. newFile = { textureUrl: url, data: fileData };
  69119. }
  69120. try {
  69121. // Put the scene into the database
  69122. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69123. addRequest.onsuccess = function (event) {
  69124. };
  69125. addRequest.onerror = function (event) {
  69126. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69127. };
  69128. }
  69129. catch (ex) {
  69130. callback(fileData);
  69131. }
  69132. }
  69133. else {
  69134. callback(fileData);
  69135. }
  69136. }
  69137. else {
  69138. callback();
  69139. }
  69140. }, false);
  69141. xhr.addEventListener("error", function (event) {
  69142. BABYLON.Tools.Error("error on XHR request.");
  69143. callback();
  69144. }, false);
  69145. xhr.send();
  69146. }
  69147. else {
  69148. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69149. callback();
  69150. }
  69151. };
  69152. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69153. Database.IsUASupportingBlobStorage = true;
  69154. /** Gets a boolean indicating if Database storate is enabled */
  69155. Database.IDBStorageEnabled = true;
  69156. Database._ParseURL = function (url) {
  69157. var a = document.createElement('a');
  69158. a.href = url;
  69159. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69160. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69161. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69162. return absLocation;
  69163. };
  69164. Database._ReturnFullUrlLocation = function (url) {
  69165. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69166. return (Database._ParseURL(window.location.href) + url);
  69167. }
  69168. else {
  69169. return url;
  69170. }
  69171. };
  69172. return Database;
  69173. }());
  69174. BABYLON.Database = Database;
  69175. })(BABYLON || (BABYLON = {}));
  69176. //# sourceMappingURL=babylon.database.js.map
  69177. var BABYLON;
  69178. (function (BABYLON) {
  69179. var FresnelParameters = /** @class */ (function () {
  69180. function FresnelParameters() {
  69181. this._isEnabled = true;
  69182. this.leftColor = BABYLON.Color3.White();
  69183. this.rightColor = BABYLON.Color3.Black();
  69184. this.bias = 0;
  69185. this.power = 1;
  69186. }
  69187. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69188. get: function () {
  69189. return this._isEnabled;
  69190. },
  69191. set: function (value) {
  69192. if (this._isEnabled === value) {
  69193. return;
  69194. }
  69195. this._isEnabled = value;
  69196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69197. },
  69198. enumerable: true,
  69199. configurable: true
  69200. });
  69201. FresnelParameters.prototype.clone = function () {
  69202. var newFresnelParameters = new FresnelParameters();
  69203. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69204. return newFresnelParameters;
  69205. };
  69206. FresnelParameters.prototype.serialize = function () {
  69207. var serializationObject = {};
  69208. serializationObject.isEnabled = this.isEnabled;
  69209. serializationObject.leftColor = this.leftColor.asArray();
  69210. serializationObject.rightColor = this.rightColor.asArray();
  69211. serializationObject.bias = this.bias;
  69212. serializationObject.power = this.power;
  69213. return serializationObject;
  69214. };
  69215. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69216. var fresnelParameters = new FresnelParameters();
  69217. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69218. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69219. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69220. fresnelParameters.bias = parsedFresnelParameters.bias;
  69221. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69222. return fresnelParameters;
  69223. };
  69224. return FresnelParameters;
  69225. }());
  69226. BABYLON.FresnelParameters = FresnelParameters;
  69227. })(BABYLON || (BABYLON = {}));
  69228. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69229. var BABYLON;
  69230. (function (BABYLON) {
  69231. var MultiMaterial = /** @class */ (function (_super) {
  69232. __extends(MultiMaterial, _super);
  69233. function MultiMaterial(name, scene) {
  69234. var _this = _super.call(this, name, scene, true) || this;
  69235. scene.multiMaterials.push(_this);
  69236. _this.subMaterials = new Array();
  69237. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69238. return _this;
  69239. }
  69240. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69241. get: function () {
  69242. return this._subMaterials;
  69243. },
  69244. set: function (value) {
  69245. this._subMaterials = value;
  69246. this._hookArray(value);
  69247. },
  69248. enumerable: true,
  69249. configurable: true
  69250. });
  69251. MultiMaterial.prototype._hookArray = function (array) {
  69252. var _this = this;
  69253. var oldPush = array.push;
  69254. array.push = function () {
  69255. var items = [];
  69256. for (var _i = 0; _i < arguments.length; _i++) {
  69257. items[_i] = arguments[_i];
  69258. }
  69259. var result = oldPush.apply(array, items);
  69260. _this._markAllSubMeshesAsTexturesDirty();
  69261. return result;
  69262. };
  69263. var oldSplice = array.splice;
  69264. array.splice = function (index, deleteCount) {
  69265. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69266. _this._markAllSubMeshesAsTexturesDirty();
  69267. return deleted;
  69268. };
  69269. };
  69270. // Properties
  69271. MultiMaterial.prototype.getSubMaterial = function (index) {
  69272. if (index < 0 || index >= this.subMaterials.length) {
  69273. return this.getScene().defaultMaterial;
  69274. }
  69275. return this.subMaterials[index];
  69276. };
  69277. MultiMaterial.prototype.getActiveTextures = function () {
  69278. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69279. if (subMaterial) {
  69280. return subMaterial.getActiveTextures();
  69281. }
  69282. else {
  69283. return [];
  69284. }
  69285. }));
  69286. var _a;
  69287. };
  69288. // Methods
  69289. MultiMaterial.prototype.getClassName = function () {
  69290. return "MultiMaterial";
  69291. };
  69292. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69293. for (var index = 0; index < this.subMaterials.length; index++) {
  69294. var subMaterial = this.subMaterials[index];
  69295. if (subMaterial) {
  69296. if (subMaterial.storeEffectOnSubMeshes) {
  69297. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69298. return false;
  69299. }
  69300. continue;
  69301. }
  69302. if (!subMaterial.isReady(mesh)) {
  69303. return false;
  69304. }
  69305. }
  69306. }
  69307. return true;
  69308. };
  69309. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69310. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69311. for (var index = 0; index < this.subMaterials.length; index++) {
  69312. var subMaterial = null;
  69313. var current = this.subMaterials[index];
  69314. if (cloneChildren && current) {
  69315. subMaterial = current.clone(name + "-" + current.name);
  69316. }
  69317. else {
  69318. subMaterial = this.subMaterials[index];
  69319. }
  69320. newMultiMaterial.subMaterials.push(subMaterial);
  69321. }
  69322. return newMultiMaterial;
  69323. };
  69324. MultiMaterial.prototype.serialize = function () {
  69325. var serializationObject = {};
  69326. serializationObject.name = this.name;
  69327. serializationObject.id = this.id;
  69328. if (BABYLON.Tags) {
  69329. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69330. }
  69331. serializationObject.materials = [];
  69332. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69333. var subMat = this.subMaterials[matIndex];
  69334. if (subMat) {
  69335. serializationObject.materials.push(subMat.id);
  69336. }
  69337. else {
  69338. serializationObject.materials.push(null);
  69339. }
  69340. }
  69341. return serializationObject;
  69342. };
  69343. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69344. var scene = this.getScene();
  69345. if (!scene) {
  69346. return;
  69347. }
  69348. var index = scene.multiMaterials.indexOf(this);
  69349. if (index >= 0) {
  69350. scene.multiMaterials.splice(index, 1);
  69351. }
  69352. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69353. };
  69354. return MultiMaterial;
  69355. }(BABYLON.Material));
  69356. BABYLON.MultiMaterial = MultiMaterial;
  69357. })(BABYLON || (BABYLON = {}));
  69358. //# sourceMappingURL=babylon.multiMaterial.js.map
  69359. var BABYLON;
  69360. (function (BABYLON) {
  69361. var FreeCameraTouchInput = /** @class */ (function () {
  69362. function FreeCameraTouchInput() {
  69363. this._offsetX = null;
  69364. this._offsetY = null;
  69365. this._pointerPressed = new Array();
  69366. this.touchAngularSensibility = 200000.0;
  69367. this.touchMoveSensibility = 250.0;
  69368. }
  69369. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69370. var _this = this;
  69371. var previousPosition = null;
  69372. if (this._pointerInput === undefined) {
  69373. this._onLostFocus = function (evt) {
  69374. _this._offsetX = null;
  69375. _this._offsetY = null;
  69376. };
  69377. this._pointerInput = function (p, s) {
  69378. var evt = p.event;
  69379. if (evt.pointerType === "mouse") {
  69380. return;
  69381. }
  69382. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69383. if (!noPreventDefault) {
  69384. evt.preventDefault();
  69385. }
  69386. _this._pointerPressed.push(evt.pointerId);
  69387. if (_this._pointerPressed.length !== 1) {
  69388. return;
  69389. }
  69390. previousPosition = {
  69391. x: evt.clientX,
  69392. y: evt.clientY
  69393. };
  69394. }
  69395. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69396. if (!noPreventDefault) {
  69397. evt.preventDefault();
  69398. }
  69399. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69400. if (index === -1) {
  69401. return;
  69402. }
  69403. _this._pointerPressed.splice(index, 1);
  69404. if (index != 0) {
  69405. return;
  69406. }
  69407. previousPosition = null;
  69408. _this._offsetX = null;
  69409. _this._offsetY = null;
  69410. }
  69411. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69412. if (!noPreventDefault) {
  69413. evt.preventDefault();
  69414. }
  69415. if (!previousPosition) {
  69416. return;
  69417. }
  69418. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69419. if (index != 0) {
  69420. return;
  69421. }
  69422. _this._offsetX = evt.clientX - previousPosition.x;
  69423. _this._offsetY = -(evt.clientY - previousPosition.y);
  69424. }
  69425. };
  69426. }
  69427. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69428. if (this._onLostFocus) {
  69429. element.addEventListener("blur", this._onLostFocus);
  69430. }
  69431. };
  69432. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69433. if (this._pointerInput && element) {
  69434. if (this._observer) {
  69435. this.camera.getScene().onPointerObservable.remove(this._observer);
  69436. this._observer = null;
  69437. }
  69438. if (this._onLostFocus) {
  69439. element.removeEventListener("blur", this._onLostFocus);
  69440. this._onLostFocus = null;
  69441. }
  69442. this._pointerPressed = [];
  69443. this._offsetX = null;
  69444. this._offsetY = null;
  69445. }
  69446. };
  69447. FreeCameraTouchInput.prototype.checkInputs = function () {
  69448. if (this._offsetX && this._offsetY) {
  69449. var camera = this.camera;
  69450. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69451. if (this._pointerPressed.length > 1) {
  69452. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69453. }
  69454. else {
  69455. var speed = camera._computeLocalCameraSpeed();
  69456. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69457. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69458. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69459. }
  69460. }
  69461. };
  69462. FreeCameraTouchInput.prototype.getClassName = function () {
  69463. return "FreeCameraTouchInput";
  69464. };
  69465. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69466. return "touch";
  69467. };
  69468. __decorate([
  69469. BABYLON.serialize()
  69470. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69471. __decorate([
  69472. BABYLON.serialize()
  69473. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69474. return FreeCameraTouchInput;
  69475. }());
  69476. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69477. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69478. })(BABYLON || (BABYLON = {}));
  69479. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69480. var BABYLON;
  69481. (function (BABYLON) {
  69482. // We're mainly based on the logic defined into the FreeCamera code
  69483. var TouchCamera = /** @class */ (function (_super) {
  69484. __extends(TouchCamera, _super);
  69485. //-- end properties for backward compatibility for inputs
  69486. function TouchCamera(name, position, scene) {
  69487. var _this = _super.call(this, name, position, scene) || this;
  69488. _this.inputs.addTouch();
  69489. _this._setupInputs();
  69490. return _this;
  69491. }
  69492. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69493. //-- Begin properties for backward compatibility for inputs
  69494. get: function () {
  69495. var touch = this.inputs.attached["touch"];
  69496. if (touch)
  69497. return touch.touchAngularSensibility;
  69498. return 0;
  69499. },
  69500. set: function (value) {
  69501. var touch = this.inputs.attached["touch"];
  69502. if (touch)
  69503. touch.touchAngularSensibility = value;
  69504. },
  69505. enumerable: true,
  69506. configurable: true
  69507. });
  69508. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69509. get: function () {
  69510. var touch = this.inputs.attached["touch"];
  69511. if (touch)
  69512. return touch.touchMoveSensibility;
  69513. return 0;
  69514. },
  69515. set: function (value) {
  69516. var touch = this.inputs.attached["touch"];
  69517. if (touch)
  69518. touch.touchMoveSensibility = value;
  69519. },
  69520. enumerable: true,
  69521. configurable: true
  69522. });
  69523. TouchCamera.prototype.getClassName = function () {
  69524. return "TouchCamera";
  69525. };
  69526. TouchCamera.prototype._setupInputs = function () {
  69527. var mouse = this.inputs.attached["mouse"];
  69528. if (mouse) {
  69529. mouse.touchEnabled = false;
  69530. }
  69531. };
  69532. return TouchCamera;
  69533. }(BABYLON.FreeCamera));
  69534. BABYLON.TouchCamera = TouchCamera;
  69535. })(BABYLON || (BABYLON = {}));
  69536. //# sourceMappingURL=babylon.touchCamera.js.map
  69537. var BABYLON;
  69538. (function (BABYLON) {
  69539. var ProceduralTexture = /** @class */ (function (_super) {
  69540. __extends(ProceduralTexture, _super);
  69541. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69542. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69543. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69544. if (isCube === void 0) { isCube = false; }
  69545. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69546. _this.isCube = isCube;
  69547. _this.isEnabled = true;
  69548. _this._currentRefreshId = -1;
  69549. _this._refreshRate = 1;
  69550. _this._vertexBuffers = {};
  69551. _this._uniforms = new Array();
  69552. _this._samplers = new Array();
  69553. _this._textures = {};
  69554. _this._floats = {};
  69555. _this._floatsArrays = {};
  69556. _this._colors3 = {};
  69557. _this._colors4 = {};
  69558. _this._vectors2 = {};
  69559. _this._vectors3 = {};
  69560. _this._matrices = {};
  69561. _this._fallbackTextureUsed = false;
  69562. scene.proceduralTextures.push(_this);
  69563. _this._engine = scene.getEngine();
  69564. _this.name = name;
  69565. _this.isRenderTarget = true;
  69566. _this._size = size;
  69567. _this._generateMipMaps = generateMipMaps;
  69568. _this.setFragment(fragment);
  69569. _this._fallbackTexture = fallbackTexture;
  69570. if (isCube) {
  69571. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69572. _this.setFloat("face", 0);
  69573. }
  69574. else {
  69575. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69576. }
  69577. // VBO
  69578. var vertices = [];
  69579. vertices.push(1, 1);
  69580. vertices.push(-1, 1);
  69581. vertices.push(-1, -1);
  69582. vertices.push(1, -1);
  69583. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69584. _this._createIndexBuffer();
  69585. return _this;
  69586. }
  69587. ProceduralTexture.prototype._createIndexBuffer = function () {
  69588. var engine = this._engine;
  69589. // Indices
  69590. var indices = [];
  69591. indices.push(0);
  69592. indices.push(1);
  69593. indices.push(2);
  69594. indices.push(0);
  69595. indices.push(2);
  69596. indices.push(3);
  69597. this._indexBuffer = engine.createIndexBuffer(indices);
  69598. };
  69599. ProceduralTexture.prototype._rebuild = function () {
  69600. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69601. if (vb) {
  69602. vb._rebuild();
  69603. }
  69604. this._createIndexBuffer();
  69605. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69606. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69607. }
  69608. };
  69609. ProceduralTexture.prototype.reset = function () {
  69610. if (this._effect === undefined) {
  69611. return;
  69612. }
  69613. var engine = this._engine;
  69614. engine._releaseEffect(this._effect);
  69615. };
  69616. ProceduralTexture.prototype.isReady = function () {
  69617. var _this = this;
  69618. var engine = this._engine;
  69619. var shaders;
  69620. if (!this._fragment) {
  69621. return false;
  69622. }
  69623. if (this._fallbackTextureUsed) {
  69624. return true;
  69625. }
  69626. if (this._fragment.fragmentElement !== undefined) {
  69627. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69628. }
  69629. else {
  69630. shaders = { vertex: "procedural", fragment: this._fragment };
  69631. }
  69632. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69633. _this.releaseInternalTexture();
  69634. if (_this._fallbackTexture) {
  69635. _this._texture = _this._fallbackTexture._texture;
  69636. if (_this._texture) {
  69637. _this._texture.incrementReferences();
  69638. }
  69639. }
  69640. _this._fallbackTextureUsed = true;
  69641. });
  69642. return this._effect.isReady();
  69643. };
  69644. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69645. this._currentRefreshId = -1;
  69646. };
  69647. ProceduralTexture.prototype.setFragment = function (fragment) {
  69648. this._fragment = fragment;
  69649. };
  69650. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69651. get: function () {
  69652. return this._refreshRate;
  69653. },
  69654. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69655. set: function (value) {
  69656. this._refreshRate = value;
  69657. this.resetRefreshCounter();
  69658. },
  69659. enumerable: true,
  69660. configurable: true
  69661. });
  69662. ProceduralTexture.prototype._shouldRender = function () {
  69663. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69664. return false;
  69665. }
  69666. if (this._fallbackTextureUsed) {
  69667. return false;
  69668. }
  69669. if (this._currentRefreshId === -1) { // At least render once
  69670. this._currentRefreshId = 1;
  69671. return true;
  69672. }
  69673. if (this.refreshRate === this._currentRefreshId) {
  69674. this._currentRefreshId = 1;
  69675. return true;
  69676. }
  69677. this._currentRefreshId++;
  69678. return false;
  69679. };
  69680. ProceduralTexture.prototype.getRenderSize = function () {
  69681. return this._size;
  69682. };
  69683. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69684. if (this._fallbackTextureUsed) {
  69685. return;
  69686. }
  69687. this.releaseInternalTexture();
  69688. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69689. };
  69690. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69691. if (this._uniforms.indexOf(uniformName) === -1) {
  69692. this._uniforms.push(uniformName);
  69693. }
  69694. };
  69695. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69696. if (this._samplers.indexOf(name) === -1) {
  69697. this._samplers.push(name);
  69698. }
  69699. this._textures[name] = texture;
  69700. return this;
  69701. };
  69702. ProceduralTexture.prototype.setFloat = function (name, value) {
  69703. this._checkUniform(name);
  69704. this._floats[name] = value;
  69705. return this;
  69706. };
  69707. ProceduralTexture.prototype.setFloats = function (name, value) {
  69708. this._checkUniform(name);
  69709. this._floatsArrays[name] = value;
  69710. return this;
  69711. };
  69712. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69713. this._checkUniform(name);
  69714. this._colors3[name] = value;
  69715. return this;
  69716. };
  69717. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69718. this._checkUniform(name);
  69719. this._colors4[name] = value;
  69720. return this;
  69721. };
  69722. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69723. this._checkUniform(name);
  69724. this._vectors2[name] = value;
  69725. return this;
  69726. };
  69727. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69728. this._checkUniform(name);
  69729. this._vectors3[name] = value;
  69730. return this;
  69731. };
  69732. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69733. this._checkUniform(name);
  69734. this._matrices[name] = value;
  69735. return this;
  69736. };
  69737. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69738. var scene = this.getScene();
  69739. if (!scene) {
  69740. return;
  69741. }
  69742. var engine = this._engine;
  69743. // Render
  69744. engine.enableEffect(this._effect);
  69745. engine.setState(false);
  69746. // Texture
  69747. for (var name in this._textures) {
  69748. this._effect.setTexture(name, this._textures[name]);
  69749. }
  69750. // Float
  69751. for (name in this._floats) {
  69752. this._effect.setFloat(name, this._floats[name]);
  69753. }
  69754. // Floats
  69755. for (name in this._floatsArrays) {
  69756. this._effect.setArray(name, this._floatsArrays[name]);
  69757. }
  69758. // Color3
  69759. for (name in this._colors3) {
  69760. this._effect.setColor3(name, this._colors3[name]);
  69761. }
  69762. // Color4
  69763. for (name in this._colors4) {
  69764. var color = this._colors4[name];
  69765. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69766. }
  69767. // Vector2
  69768. for (name in this._vectors2) {
  69769. this._effect.setVector2(name, this._vectors2[name]);
  69770. }
  69771. // Vector3
  69772. for (name in this._vectors3) {
  69773. this._effect.setVector3(name, this._vectors3[name]);
  69774. }
  69775. // Matrix
  69776. for (name in this._matrices) {
  69777. this._effect.setMatrix(name, this._matrices[name]);
  69778. }
  69779. if (!this._texture) {
  69780. return;
  69781. }
  69782. if (this.isCube) {
  69783. for (var face = 0; face < 6; face++) {
  69784. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69785. // VBOs
  69786. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69787. this._effect.setFloat("face", face);
  69788. // Clear
  69789. engine.clear(scene.clearColor, true, true, true);
  69790. // Draw order
  69791. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69792. // Mipmaps
  69793. if (face === 5) {
  69794. engine.generateMipMapsForCubemap(this._texture);
  69795. }
  69796. }
  69797. }
  69798. else {
  69799. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69800. // VBOs
  69801. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69802. // Clear
  69803. engine.clear(scene.clearColor, true, true, true);
  69804. // Draw order
  69805. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69806. }
  69807. // Unbind
  69808. engine.unBindFramebuffer(this._texture, this.isCube);
  69809. if (this.onGenerated) {
  69810. this.onGenerated();
  69811. }
  69812. };
  69813. ProceduralTexture.prototype.clone = function () {
  69814. var textureSize = this.getSize();
  69815. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69816. // Base texture
  69817. newTexture.hasAlpha = this.hasAlpha;
  69818. newTexture.level = this.level;
  69819. // RenderTarget Texture
  69820. newTexture.coordinatesMode = this.coordinatesMode;
  69821. return newTexture;
  69822. };
  69823. ProceduralTexture.prototype.dispose = function () {
  69824. var scene = this.getScene();
  69825. if (!scene) {
  69826. return;
  69827. }
  69828. var index = scene.proceduralTextures.indexOf(this);
  69829. if (index >= 0) {
  69830. scene.proceduralTextures.splice(index, 1);
  69831. }
  69832. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69833. if (vertexBuffer) {
  69834. vertexBuffer.dispose();
  69835. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69836. }
  69837. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69838. this._indexBuffer = null;
  69839. }
  69840. _super.prototype.dispose.call(this);
  69841. };
  69842. return ProceduralTexture;
  69843. }(BABYLON.Texture));
  69844. BABYLON.ProceduralTexture = ProceduralTexture;
  69845. })(BABYLON || (BABYLON = {}));
  69846. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69847. var BABYLON;
  69848. (function (BABYLON) {
  69849. var CustomProceduralTexture = /** @class */ (function (_super) {
  69850. __extends(CustomProceduralTexture, _super);
  69851. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69852. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69853. _this._animate = true;
  69854. _this._time = 0;
  69855. _this._texturePath = texturePath;
  69856. //Try to load json
  69857. _this.loadJson(texturePath);
  69858. _this.refreshRate = 1;
  69859. return _this;
  69860. }
  69861. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69862. var _this = this;
  69863. var noConfigFile = function () {
  69864. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69865. try {
  69866. _this.setFragment(_this._texturePath);
  69867. }
  69868. catch (ex) {
  69869. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69870. }
  69871. };
  69872. var configFileUrl = jsonUrl + "/config.json";
  69873. var xhr = new XMLHttpRequest();
  69874. xhr.open("GET", configFileUrl, true);
  69875. xhr.addEventListener("load", function () {
  69876. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69877. try {
  69878. _this._config = JSON.parse(xhr.response);
  69879. _this.updateShaderUniforms();
  69880. _this.updateTextures();
  69881. _this.setFragment(_this._texturePath + "/custom");
  69882. _this._animate = _this._config.animate;
  69883. _this.refreshRate = _this._config.refreshrate;
  69884. }
  69885. catch (ex) {
  69886. noConfigFile();
  69887. }
  69888. }
  69889. else {
  69890. noConfigFile();
  69891. }
  69892. }, false);
  69893. xhr.addEventListener("error", function () {
  69894. noConfigFile();
  69895. }, false);
  69896. try {
  69897. xhr.send();
  69898. }
  69899. catch (ex) {
  69900. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69901. }
  69902. };
  69903. CustomProceduralTexture.prototype.isReady = function () {
  69904. if (!_super.prototype.isReady.call(this)) {
  69905. return false;
  69906. }
  69907. for (var name in this._textures) {
  69908. var texture = this._textures[name];
  69909. if (!texture.isReady()) {
  69910. return false;
  69911. }
  69912. }
  69913. return true;
  69914. };
  69915. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69916. var scene = this.getScene();
  69917. if (this._animate && scene) {
  69918. this._time += scene.getAnimationRatio() * 0.03;
  69919. this.updateShaderUniforms();
  69920. }
  69921. _super.prototype.render.call(this, useCameraPostProcess);
  69922. };
  69923. CustomProceduralTexture.prototype.updateTextures = function () {
  69924. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69925. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69926. }
  69927. };
  69928. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69929. if (this._config) {
  69930. for (var j = 0; j < this._config.uniforms.length; j++) {
  69931. var uniform = this._config.uniforms[j];
  69932. switch (uniform.type) {
  69933. case "float":
  69934. this.setFloat(uniform.name, uniform.value);
  69935. break;
  69936. case "color3":
  69937. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69938. break;
  69939. case "color4":
  69940. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69941. break;
  69942. case "vector2":
  69943. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69944. break;
  69945. case "vector3":
  69946. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69947. break;
  69948. }
  69949. }
  69950. }
  69951. this.setFloat("time", this._time);
  69952. };
  69953. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69954. get: function () {
  69955. return this._animate;
  69956. },
  69957. set: function (value) {
  69958. this._animate = value;
  69959. },
  69960. enumerable: true,
  69961. configurable: true
  69962. });
  69963. return CustomProceduralTexture;
  69964. }(BABYLON.ProceduralTexture));
  69965. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69966. })(BABYLON || (BABYLON = {}));
  69967. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69968. var BABYLON;
  69969. (function (BABYLON) {
  69970. var FreeCameraGamepadInput = /** @class */ (function () {
  69971. function FreeCameraGamepadInput() {
  69972. this.gamepadAngularSensibility = 200;
  69973. this.gamepadMoveSensibility = 40;
  69974. // private members
  69975. this._cameraTransform = BABYLON.Matrix.Identity();
  69976. this._deltaTransform = BABYLON.Vector3.Zero();
  69977. this._vector3 = BABYLON.Vector3.Zero();
  69978. this._vector2 = BABYLON.Vector2.Zero();
  69979. }
  69980. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69981. var _this = this;
  69982. var manager = this.camera.getScene().gamepadManager;
  69983. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69984. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69985. // prioritize XBOX gamepads.
  69986. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69987. _this.gamepad = gamepad;
  69988. }
  69989. }
  69990. });
  69991. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69992. if (_this.gamepad === gamepad) {
  69993. _this.gamepad = null;
  69994. }
  69995. });
  69996. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69997. };
  69998. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69999. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70000. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70001. this.gamepad = null;
  70002. };
  70003. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70004. if (this.gamepad && this.gamepad.leftStick) {
  70005. var camera = this.camera;
  70006. var LSValues = this.gamepad.leftStick;
  70007. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70008. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70009. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70010. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70011. var RSValues = this.gamepad.rightStick;
  70012. if (RSValues) {
  70013. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70014. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70015. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70016. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70017. }
  70018. else {
  70019. RSValues = { x: 0, y: 0 };
  70020. }
  70021. if (!camera.rotationQuaternion) {
  70022. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70023. }
  70024. else {
  70025. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70026. }
  70027. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70028. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70029. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70030. camera.cameraDirection.addInPlace(this._deltaTransform);
  70031. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70032. camera.cameraRotation.addInPlace(this._vector2);
  70033. }
  70034. };
  70035. FreeCameraGamepadInput.prototype.getClassName = function () {
  70036. return "FreeCameraGamepadInput";
  70037. };
  70038. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70039. return "gamepad";
  70040. };
  70041. __decorate([
  70042. BABYLON.serialize()
  70043. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70044. __decorate([
  70045. BABYLON.serialize()
  70046. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70047. return FreeCameraGamepadInput;
  70048. }());
  70049. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70050. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70051. })(BABYLON || (BABYLON = {}));
  70052. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70053. var BABYLON;
  70054. (function (BABYLON) {
  70055. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70056. function ArcRotateCameraGamepadInput() {
  70057. this.gamepadRotationSensibility = 80;
  70058. this.gamepadMoveSensibility = 40;
  70059. }
  70060. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70061. var _this = this;
  70062. var manager = this.camera.getScene().gamepadManager;
  70063. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70064. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70065. // prioritize XBOX gamepads.
  70066. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70067. _this.gamepad = gamepad;
  70068. }
  70069. }
  70070. });
  70071. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70072. if (_this.gamepad === gamepad) {
  70073. _this.gamepad = null;
  70074. }
  70075. });
  70076. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70077. };
  70078. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70079. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70080. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70081. this.gamepad = null;
  70082. };
  70083. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70084. if (this.gamepad) {
  70085. var camera = this.camera;
  70086. var RSValues = this.gamepad.rightStick;
  70087. if (RSValues) {
  70088. if (RSValues.x != 0) {
  70089. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70090. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70091. camera.inertialAlphaOffset += normalizedRX;
  70092. }
  70093. }
  70094. if (RSValues.y != 0) {
  70095. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70096. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70097. camera.inertialBetaOffset += normalizedRY;
  70098. }
  70099. }
  70100. }
  70101. var LSValues = this.gamepad.leftStick;
  70102. if (LSValues && LSValues.y != 0) {
  70103. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70104. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70105. this.camera.inertialRadiusOffset -= normalizedLY;
  70106. }
  70107. }
  70108. }
  70109. };
  70110. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70111. return "ArcRotateCameraGamepadInput";
  70112. };
  70113. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70114. return "gamepad";
  70115. };
  70116. __decorate([
  70117. BABYLON.serialize()
  70118. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70119. __decorate([
  70120. BABYLON.serialize()
  70121. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70122. return ArcRotateCameraGamepadInput;
  70123. }());
  70124. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70125. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70126. })(BABYLON || (BABYLON = {}));
  70127. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70128. var BABYLON;
  70129. (function (BABYLON) {
  70130. var GamepadManager = /** @class */ (function () {
  70131. function GamepadManager(_scene) {
  70132. var _this = this;
  70133. this._scene = _scene;
  70134. this._babylonGamepads = [];
  70135. this._oneGamepadConnected = false;
  70136. this._isMonitoring = false;
  70137. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70138. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70139. this._gamepadEventSupported = false;
  70140. }
  70141. else {
  70142. this._gamepadEventSupported = 'GamepadEvent' in window;
  70143. this._gamepadSupport = (navigator.getGamepads ||
  70144. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70145. }
  70146. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70147. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70148. for (var i in _this._babylonGamepads) {
  70149. var gamepad = _this._babylonGamepads[i];
  70150. if (gamepad && gamepad._isConnected) {
  70151. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70152. }
  70153. }
  70154. });
  70155. this._onGamepadConnectedEvent = function (evt) {
  70156. var gamepad = evt.gamepad;
  70157. if (gamepad.index in _this._babylonGamepads) {
  70158. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70159. return;
  70160. }
  70161. }
  70162. var newGamepad;
  70163. if (_this._babylonGamepads[gamepad.index]) {
  70164. newGamepad = _this._babylonGamepads[gamepad.index];
  70165. newGamepad.browserGamepad = gamepad;
  70166. newGamepad._isConnected = true;
  70167. }
  70168. else {
  70169. newGamepad = _this._addNewGamepad(gamepad);
  70170. }
  70171. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70172. _this._startMonitoringGamepads();
  70173. };
  70174. this._onGamepadDisconnectedEvent = function (evt) {
  70175. var gamepad = evt.gamepad;
  70176. // Remove the gamepad from the list of gamepads to monitor.
  70177. for (var i in _this._babylonGamepads) {
  70178. if (_this._babylonGamepads[i].index === gamepad.index) {
  70179. var disconnectedGamepad = _this._babylonGamepads[i];
  70180. disconnectedGamepad._isConnected = false;
  70181. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70182. break;
  70183. }
  70184. }
  70185. };
  70186. if (this._gamepadSupport) {
  70187. //first add already-connected gamepads
  70188. this._updateGamepadObjects();
  70189. if (this._babylonGamepads.length) {
  70190. this._startMonitoringGamepads();
  70191. }
  70192. // Checking if the gamepad connected event is supported (like in Firefox)
  70193. if (this._gamepadEventSupported) {
  70194. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70195. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70196. }
  70197. else {
  70198. this._startMonitoringGamepads();
  70199. }
  70200. }
  70201. }
  70202. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70203. get: function () {
  70204. return this._babylonGamepads;
  70205. },
  70206. enumerable: true,
  70207. configurable: true
  70208. });
  70209. GamepadManager.prototype.getGamepadByType = function (type) {
  70210. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70211. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70212. var gamepad = _a[_i];
  70213. if (gamepad && gamepad.type === type) {
  70214. return gamepad;
  70215. }
  70216. }
  70217. return null;
  70218. };
  70219. GamepadManager.prototype.dispose = function () {
  70220. if (this._gamepadEventSupported) {
  70221. if (this._onGamepadConnectedEvent) {
  70222. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70223. }
  70224. if (this._onGamepadDisconnectedEvent) {
  70225. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70226. }
  70227. this._onGamepadConnectedEvent = null;
  70228. this._onGamepadDisconnectedEvent = null;
  70229. }
  70230. this._babylonGamepads.forEach(function (gamepad) {
  70231. gamepad.dispose();
  70232. });
  70233. this.onGamepadConnectedObservable.clear();
  70234. this.onGamepadDisconnectedObservable.clear();
  70235. this._oneGamepadConnected = false;
  70236. this._stopMonitoringGamepads();
  70237. this._babylonGamepads = [];
  70238. };
  70239. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70240. if (!this._oneGamepadConnected) {
  70241. this._oneGamepadConnected = true;
  70242. }
  70243. var newGamepad;
  70244. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70245. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70246. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70247. }
  70248. // if pose is supported, use the (WebVR) pose enabled controller
  70249. else if (gamepad.pose) {
  70250. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70251. }
  70252. else {
  70253. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70254. }
  70255. this._babylonGamepads[newGamepad.index] = newGamepad;
  70256. return newGamepad;
  70257. };
  70258. GamepadManager.prototype._startMonitoringGamepads = function () {
  70259. if (!this._isMonitoring) {
  70260. this._isMonitoring = true;
  70261. //back-comp
  70262. if (!this._scene) {
  70263. this._checkGamepadsStatus();
  70264. }
  70265. }
  70266. };
  70267. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70268. this._isMonitoring = false;
  70269. };
  70270. GamepadManager.prototype._checkGamepadsStatus = function () {
  70271. var _this = this;
  70272. // Hack to be compatible Chrome
  70273. this._updateGamepadObjects();
  70274. for (var i in this._babylonGamepads) {
  70275. var gamepad = this._babylonGamepads[i];
  70276. if (!gamepad || !gamepad.isConnected) {
  70277. continue;
  70278. }
  70279. gamepad.update();
  70280. }
  70281. if (this._isMonitoring && !this._scene) {
  70282. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70283. }
  70284. };
  70285. // This function is called only on Chrome, which does not properly support
  70286. // connection/disconnection events and forces you to recopy again the gamepad object
  70287. GamepadManager.prototype._updateGamepadObjects = function () {
  70288. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70289. for (var i = 0; i < gamepads.length; i++) {
  70290. var gamepad = gamepads[i];
  70291. if (gamepad) {
  70292. if (!this._babylonGamepads[gamepad.index]) {
  70293. var newGamepad = this._addNewGamepad(gamepad);
  70294. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70295. }
  70296. else {
  70297. // Forced to copy again this object for Chrome for unknown reason
  70298. this._babylonGamepads[i].browserGamepad = gamepad;
  70299. if (!this._babylonGamepads[i].isConnected) {
  70300. this._babylonGamepads[i]._isConnected = true;
  70301. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70302. }
  70303. }
  70304. }
  70305. }
  70306. };
  70307. return GamepadManager;
  70308. }());
  70309. BABYLON.GamepadManager = GamepadManager;
  70310. })(BABYLON || (BABYLON = {}));
  70311. //# sourceMappingURL=babylon.gamepadManager.js.map
  70312. var BABYLON;
  70313. (function (BABYLON) {
  70314. var StickValues = /** @class */ (function () {
  70315. function StickValues(x, y) {
  70316. this.x = x;
  70317. this.y = y;
  70318. }
  70319. return StickValues;
  70320. }());
  70321. BABYLON.StickValues = StickValues;
  70322. var Gamepad = /** @class */ (function () {
  70323. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70324. if (leftStickX === void 0) { leftStickX = 0; }
  70325. if (leftStickY === void 0) { leftStickY = 1; }
  70326. if (rightStickX === void 0) { rightStickX = 2; }
  70327. if (rightStickY === void 0) { rightStickY = 3; }
  70328. this.id = id;
  70329. this.index = index;
  70330. this.browserGamepad = browserGamepad;
  70331. this._isConnected = true;
  70332. this._invertLeftStickY = false;
  70333. this.type = Gamepad.GAMEPAD;
  70334. this._leftStickAxisX = leftStickX;
  70335. this._leftStickAxisY = leftStickY;
  70336. this._rightStickAxisX = rightStickX;
  70337. this._rightStickAxisY = rightStickY;
  70338. if (this.browserGamepad.axes.length >= 2) {
  70339. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70340. }
  70341. if (this.browserGamepad.axes.length >= 4) {
  70342. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70343. }
  70344. }
  70345. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70346. get: function () {
  70347. return this._isConnected;
  70348. },
  70349. enumerable: true,
  70350. configurable: true
  70351. });
  70352. Gamepad.prototype.onleftstickchanged = function (callback) {
  70353. this._onleftstickchanged = callback;
  70354. };
  70355. Gamepad.prototype.onrightstickchanged = function (callback) {
  70356. this._onrightstickchanged = callback;
  70357. };
  70358. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70359. get: function () {
  70360. return this._leftStick;
  70361. },
  70362. set: function (newValues) {
  70363. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70364. this._onleftstickchanged(newValues);
  70365. }
  70366. this._leftStick = newValues;
  70367. },
  70368. enumerable: true,
  70369. configurable: true
  70370. });
  70371. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70372. get: function () {
  70373. return this._rightStick;
  70374. },
  70375. set: function (newValues) {
  70376. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70377. this._onrightstickchanged(newValues);
  70378. }
  70379. this._rightStick = newValues;
  70380. },
  70381. enumerable: true,
  70382. configurable: true
  70383. });
  70384. Gamepad.prototype.update = function () {
  70385. if (this._leftStick) {
  70386. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70387. if (this._invertLeftStickY) {
  70388. this.leftStick.y *= -1;
  70389. }
  70390. }
  70391. if (this._rightStick) {
  70392. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70393. }
  70394. };
  70395. Gamepad.prototype.dispose = function () {
  70396. };
  70397. Gamepad.GAMEPAD = 0;
  70398. Gamepad.GENERIC = 1;
  70399. Gamepad.XBOX = 2;
  70400. Gamepad.POSE_ENABLED = 3;
  70401. return Gamepad;
  70402. }());
  70403. BABYLON.Gamepad = Gamepad;
  70404. var GenericPad = /** @class */ (function (_super) {
  70405. __extends(GenericPad, _super);
  70406. function GenericPad(id, index, browserGamepad) {
  70407. var _this = _super.call(this, id, index, browserGamepad) || this;
  70408. _this.onButtonDownObservable = new BABYLON.Observable();
  70409. _this.onButtonUpObservable = new BABYLON.Observable();
  70410. _this.type = Gamepad.GENERIC;
  70411. _this._buttons = new Array(browserGamepad.buttons.length);
  70412. return _this;
  70413. }
  70414. GenericPad.prototype.onbuttondown = function (callback) {
  70415. this._onbuttondown = callback;
  70416. };
  70417. GenericPad.prototype.onbuttonup = function (callback) {
  70418. this._onbuttonup = callback;
  70419. };
  70420. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70421. if (newValue !== currentValue) {
  70422. if (newValue === 1) {
  70423. if (this._onbuttondown) {
  70424. this._onbuttondown(buttonIndex);
  70425. }
  70426. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70427. }
  70428. if (newValue === 0) {
  70429. if (this._onbuttonup) {
  70430. this._onbuttonup(buttonIndex);
  70431. }
  70432. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70433. }
  70434. }
  70435. return newValue;
  70436. };
  70437. GenericPad.prototype.update = function () {
  70438. _super.prototype.update.call(this);
  70439. for (var index = 0; index < this._buttons.length; index++) {
  70440. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70441. }
  70442. };
  70443. GenericPad.prototype.dispose = function () {
  70444. _super.prototype.dispose.call(this);
  70445. this.onButtonDownObservable.clear();
  70446. this.onButtonUpObservable.clear();
  70447. };
  70448. return GenericPad;
  70449. }(Gamepad));
  70450. BABYLON.GenericPad = GenericPad;
  70451. })(BABYLON || (BABYLON = {}));
  70452. //# sourceMappingURL=babylon.gamepad.js.map
  70453. var BABYLON;
  70454. (function (BABYLON) {
  70455. /**
  70456. * Defines supported buttons for XBox360 compatible gamepads
  70457. */
  70458. var Xbox360Button;
  70459. (function (Xbox360Button) {
  70460. /** A */
  70461. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70462. /** B */
  70463. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70464. /** X */
  70465. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70466. /** Y */
  70467. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70468. /** Start */
  70469. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70470. /** Back */
  70471. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70472. /** Left button */
  70473. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70474. /** Right button */
  70475. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70476. /** Left stick */
  70477. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70478. /** Right stick */
  70479. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70480. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70481. /** Defines values for XBox360 DPad */
  70482. var Xbox360Dpad;
  70483. (function (Xbox360Dpad) {
  70484. /** Up */
  70485. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70486. /** Down */
  70487. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70488. /** Left */
  70489. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70490. /** Right */
  70491. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70492. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70493. /**
  70494. * Defines a XBox360 gamepad
  70495. */
  70496. var Xbox360Pad = /** @class */ (function (_super) {
  70497. __extends(Xbox360Pad, _super);
  70498. /**
  70499. * Creates a new XBox360 gamepad object
  70500. * @param id defines the id of this gamepad
  70501. * @param index defines its index
  70502. * @param gamepad defines the internal HTML gamepad object
  70503. * @param xboxOne defines if it is a XBox One gamepad
  70504. */
  70505. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70506. if (xboxOne === void 0) { xboxOne = false; }
  70507. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70508. _this._leftTrigger = 0;
  70509. _this._rightTrigger = 0;
  70510. /** Observable raised when a button is pressed */
  70511. _this.onButtonDownObservable = new BABYLON.Observable();
  70512. /** Observable raised when a button is released */
  70513. _this.onButtonUpObservable = new BABYLON.Observable();
  70514. /** Observable raised when a pad is pressed */
  70515. _this.onPadDownObservable = new BABYLON.Observable();
  70516. /** Observable raised when a pad is released */
  70517. _this.onPadUpObservable = new BABYLON.Observable();
  70518. _this._buttonA = 0;
  70519. _this._buttonB = 0;
  70520. _this._buttonX = 0;
  70521. _this._buttonY = 0;
  70522. _this._buttonBack = 0;
  70523. _this._buttonStart = 0;
  70524. _this._buttonLB = 0;
  70525. _this._buttonRB = 0;
  70526. _this._buttonLeftStick = 0;
  70527. _this._buttonRightStick = 0;
  70528. _this._dPadUp = 0;
  70529. _this._dPadDown = 0;
  70530. _this._dPadLeft = 0;
  70531. _this._dPadRight = 0;
  70532. _this._isXboxOnePad = false;
  70533. _this.type = BABYLON.Gamepad.XBOX;
  70534. _this._isXboxOnePad = xboxOne;
  70535. return _this;
  70536. }
  70537. /**
  70538. * Defines the callback to call when left trigger is pressed
  70539. * @param callback defines the callback to use
  70540. */
  70541. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70542. this._onlefttriggerchanged = callback;
  70543. };
  70544. /**
  70545. * Defines the callback to call when right trigger is pressed
  70546. * @param callback defines the callback to use
  70547. */
  70548. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70549. this._onrighttriggerchanged = callback;
  70550. };
  70551. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70552. /**
  70553. * Gets or sets left trigger value
  70554. */
  70555. get: function () {
  70556. return this._leftTrigger;
  70557. },
  70558. set: function (newValue) {
  70559. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70560. this._onlefttriggerchanged(newValue);
  70561. }
  70562. this._leftTrigger = newValue;
  70563. },
  70564. enumerable: true,
  70565. configurable: true
  70566. });
  70567. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70568. /**
  70569. * Gets or sets right trigger value
  70570. */
  70571. get: function () {
  70572. return this._rightTrigger;
  70573. },
  70574. set: function (newValue) {
  70575. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70576. this._onrighttriggerchanged(newValue);
  70577. }
  70578. this._rightTrigger = newValue;
  70579. },
  70580. enumerable: true,
  70581. configurable: true
  70582. });
  70583. /**
  70584. * Defines the callback to call when a button is pressed
  70585. * @param callback defines the callback to use
  70586. */
  70587. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70588. this._onbuttondown = callback;
  70589. };
  70590. /**
  70591. * Defines the callback to call when a button is released
  70592. * @param callback defines the callback to use
  70593. */
  70594. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70595. this._onbuttonup = callback;
  70596. };
  70597. /**
  70598. * Defines the callback to call when a pad is pressed
  70599. * @param callback defines the callback to use
  70600. */
  70601. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70602. this._ondpaddown = callback;
  70603. };
  70604. /**
  70605. * Defines the callback to call when a pad is released
  70606. * @param callback defines the callback to use
  70607. */
  70608. Xbox360Pad.prototype.ondpadup = function (callback) {
  70609. this._ondpadup = callback;
  70610. };
  70611. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70612. if (newValue !== currentValue) {
  70613. if (newValue === 1) {
  70614. if (this._onbuttondown) {
  70615. this._onbuttondown(buttonType);
  70616. }
  70617. this.onButtonDownObservable.notifyObservers(buttonType);
  70618. }
  70619. if (newValue === 0) {
  70620. if (this._onbuttonup) {
  70621. this._onbuttonup(buttonType);
  70622. }
  70623. this.onButtonUpObservable.notifyObservers(buttonType);
  70624. }
  70625. }
  70626. return newValue;
  70627. };
  70628. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70629. if (newValue !== currentValue) {
  70630. if (newValue === 1) {
  70631. if (this._ondpaddown) {
  70632. this._ondpaddown(buttonType);
  70633. }
  70634. this.onPadDownObservable.notifyObservers(buttonType);
  70635. }
  70636. if (newValue === 0) {
  70637. if (this._ondpadup) {
  70638. this._ondpadup(buttonType);
  70639. }
  70640. this.onPadUpObservable.notifyObservers(buttonType);
  70641. }
  70642. }
  70643. return newValue;
  70644. };
  70645. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70646. /** Gets or sets value of A button */
  70647. get: function () {
  70648. return this._buttonA;
  70649. },
  70650. set: function (value) {
  70651. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70652. },
  70653. enumerable: true,
  70654. configurable: true
  70655. });
  70656. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70657. /** Gets or sets value of B button */
  70658. get: function () {
  70659. return this._buttonB;
  70660. },
  70661. set: function (value) {
  70662. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70663. },
  70664. enumerable: true,
  70665. configurable: true
  70666. });
  70667. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70668. /** Gets or sets value of X button */
  70669. get: function () {
  70670. return this._buttonX;
  70671. },
  70672. set: function (value) {
  70673. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70674. },
  70675. enumerable: true,
  70676. configurable: true
  70677. });
  70678. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70679. /** Gets or sets value of Y button */
  70680. get: function () {
  70681. return this._buttonY;
  70682. },
  70683. set: function (value) {
  70684. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70685. },
  70686. enumerable: true,
  70687. configurable: true
  70688. });
  70689. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70690. /** Gets or sets value of Start button */
  70691. get: function () {
  70692. return this._buttonStart;
  70693. },
  70694. set: function (value) {
  70695. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70696. },
  70697. enumerable: true,
  70698. configurable: true
  70699. });
  70700. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70701. /** Gets or sets value of Back button */
  70702. get: function () {
  70703. return this._buttonBack;
  70704. },
  70705. set: function (value) {
  70706. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70707. },
  70708. enumerable: true,
  70709. configurable: true
  70710. });
  70711. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70712. /** Gets or sets value of Left button */
  70713. get: function () {
  70714. return this._buttonLB;
  70715. },
  70716. set: function (value) {
  70717. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70718. },
  70719. enumerable: true,
  70720. configurable: true
  70721. });
  70722. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70723. /** Gets or sets value of Right button */
  70724. get: function () {
  70725. return this._buttonRB;
  70726. },
  70727. set: function (value) {
  70728. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70729. },
  70730. enumerable: true,
  70731. configurable: true
  70732. });
  70733. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70734. /** Gets or sets value of left stick */
  70735. get: function () {
  70736. return this._buttonLeftStick;
  70737. },
  70738. set: function (value) {
  70739. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70740. },
  70741. enumerable: true,
  70742. configurable: true
  70743. });
  70744. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70745. /** Gets or sets value of right stick */
  70746. get: function () {
  70747. return this._buttonRightStick;
  70748. },
  70749. set: function (value) {
  70750. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70751. },
  70752. enumerable: true,
  70753. configurable: true
  70754. });
  70755. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70756. /** Gets or sets value of DPad up */
  70757. get: function () {
  70758. return this._dPadUp;
  70759. },
  70760. set: function (value) {
  70761. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70762. },
  70763. enumerable: true,
  70764. configurable: true
  70765. });
  70766. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70767. /** Gets or sets value of DPad down */
  70768. get: function () {
  70769. return this._dPadDown;
  70770. },
  70771. set: function (value) {
  70772. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70773. },
  70774. enumerable: true,
  70775. configurable: true
  70776. });
  70777. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70778. /** Gets or sets value of DPad left */
  70779. get: function () {
  70780. return this._dPadLeft;
  70781. },
  70782. set: function (value) {
  70783. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70784. },
  70785. enumerable: true,
  70786. configurable: true
  70787. });
  70788. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70789. /** Gets or sets value of DPad right */
  70790. get: function () {
  70791. return this._dPadRight;
  70792. },
  70793. set: function (value) {
  70794. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70795. },
  70796. enumerable: true,
  70797. configurable: true
  70798. });
  70799. /**
  70800. * Force the gamepad to synchronize with device values
  70801. */
  70802. Xbox360Pad.prototype.update = function () {
  70803. _super.prototype.update.call(this);
  70804. if (this._isXboxOnePad) {
  70805. this.buttonA = this.browserGamepad.buttons[0].value;
  70806. this.buttonB = this.browserGamepad.buttons[1].value;
  70807. this.buttonX = this.browserGamepad.buttons[2].value;
  70808. this.buttonY = this.browserGamepad.buttons[3].value;
  70809. this.buttonLB = this.browserGamepad.buttons[4].value;
  70810. this.buttonRB = this.browserGamepad.buttons[5].value;
  70811. this.leftTrigger = this.browserGamepad.axes[2];
  70812. this.rightTrigger = this.browserGamepad.axes[5];
  70813. this.buttonBack = this.browserGamepad.buttons[9].value;
  70814. this.buttonStart = this.browserGamepad.buttons[8].value;
  70815. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70816. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70817. this.dPadUp = this.browserGamepad.buttons[11].value;
  70818. this.dPadDown = this.browserGamepad.buttons[12].value;
  70819. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70820. this.dPadRight = this.browserGamepad.buttons[14].value;
  70821. }
  70822. else {
  70823. this.buttonA = this.browserGamepad.buttons[0].value;
  70824. this.buttonB = this.browserGamepad.buttons[1].value;
  70825. this.buttonX = this.browserGamepad.buttons[2].value;
  70826. this.buttonY = this.browserGamepad.buttons[3].value;
  70827. this.buttonLB = this.browserGamepad.buttons[4].value;
  70828. this.buttonRB = this.browserGamepad.buttons[5].value;
  70829. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70830. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70831. this.buttonBack = this.browserGamepad.buttons[8].value;
  70832. this.buttonStart = this.browserGamepad.buttons[9].value;
  70833. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70834. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70835. this.dPadUp = this.browserGamepad.buttons[12].value;
  70836. this.dPadDown = this.browserGamepad.buttons[13].value;
  70837. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70838. this.dPadRight = this.browserGamepad.buttons[15].value;
  70839. }
  70840. };
  70841. Xbox360Pad.prototype.dispose = function () {
  70842. _super.prototype.dispose.call(this);
  70843. this.onButtonDownObservable.clear();
  70844. this.onButtonUpObservable.clear();
  70845. this.onPadDownObservable.clear();
  70846. this.onPadUpObservable.clear();
  70847. };
  70848. return Xbox360Pad;
  70849. }(BABYLON.Gamepad));
  70850. BABYLON.Xbox360Pad = Xbox360Pad;
  70851. })(BABYLON || (BABYLON = {}));
  70852. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70853. var BABYLON;
  70854. (function (BABYLON) {
  70855. /**
  70856. * Defines the types of pose enabled controllers that are supported
  70857. */
  70858. var PoseEnabledControllerType;
  70859. (function (PoseEnabledControllerType) {
  70860. /**
  70861. * HTC Vive
  70862. */
  70863. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70864. /**
  70865. * Oculus Rift
  70866. */
  70867. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70868. /**
  70869. * Windows mixed reality
  70870. */
  70871. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70872. /**
  70873. * Samsung gear VR
  70874. */
  70875. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70876. /**
  70877. * Google Daydream
  70878. */
  70879. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70880. /**
  70881. * Generic
  70882. */
  70883. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70884. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70885. /**
  70886. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70887. */
  70888. var PoseEnabledControllerHelper = /** @class */ (function () {
  70889. function PoseEnabledControllerHelper() {
  70890. }
  70891. /**
  70892. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70893. * @param vrGamepad the gamepad to initialized
  70894. * @returns a vr controller of the type the gamepad identified as
  70895. */
  70896. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70897. // Oculus Touch
  70898. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70899. return new BABYLON.OculusTouchController(vrGamepad);
  70900. }
  70901. // Windows Mixed Reality controllers
  70902. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70903. return new BABYLON.WindowsMotionController(vrGamepad);
  70904. }
  70905. // HTC Vive
  70906. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70907. return new BABYLON.ViveController(vrGamepad);
  70908. }
  70909. // Samsung/Oculus Gear VR
  70910. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70911. return new BABYLON.GearVRController(vrGamepad);
  70912. }
  70913. // Google Daydream
  70914. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70915. return new BABYLON.DaydreamController(vrGamepad);
  70916. }
  70917. // Generic
  70918. else {
  70919. return new BABYLON.GenericController(vrGamepad);
  70920. }
  70921. };
  70922. return PoseEnabledControllerHelper;
  70923. }());
  70924. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70925. /**
  70926. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70927. */
  70928. var PoseEnabledController = /** @class */ (function (_super) {
  70929. __extends(PoseEnabledController, _super);
  70930. /**
  70931. * Creates a new PoseEnabledController from a gamepad
  70932. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70933. */
  70934. function PoseEnabledController(browserGamepad) {
  70935. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70936. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70937. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70938. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70939. /**
  70940. * The device position in babylon space
  70941. */
  70942. _this.devicePosition = BABYLON.Vector3.Zero();
  70943. /**
  70944. * The device rotation in babylon space
  70945. */
  70946. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70947. /**
  70948. * The scale factor of the device in babylon space
  70949. */
  70950. _this.deviceScaleFactor = 1;
  70951. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70952. /**
  70953. * Internal, matrix used to convert room space to babylon space
  70954. */
  70955. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70956. /**
  70957. * Node to be used when casting a ray from the controller
  70958. */
  70959. _this._pointingPoseNode = null;
  70960. _this._workingMatrix = BABYLON.Matrix.Identity();
  70961. /**
  70962. * @hidden
  70963. */
  70964. _this._meshAttachedObservable = new BABYLON.Observable();
  70965. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70966. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70967. _this.position = BABYLON.Vector3.Zero();
  70968. _this.rotationQuaternion = new BABYLON.Quaternion();
  70969. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70970. _this._calculatedRotation = new BABYLON.Quaternion();
  70971. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70972. return _this;
  70973. }
  70974. /**
  70975. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70976. */
  70977. PoseEnabledController.prototype.update = function () {
  70978. _super.prototype.update.call(this);
  70979. var pose = this.browserGamepad.pose;
  70980. this.updateFromDevice(pose);
  70981. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70982. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70983. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70984. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70985. if (this._mesh) {
  70986. this._mesh.position.copyFrom(this.devicePosition);
  70987. if (this._mesh.rotationQuaternion) {
  70988. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70989. }
  70990. }
  70991. };
  70992. /**
  70993. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70994. * @param poseData raw pose fromthe device
  70995. */
  70996. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70997. if (poseData) {
  70998. this.rawPose = poseData;
  70999. if (poseData.position) {
  71000. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71001. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71002. this._deviceRoomPosition.z *= -1;
  71003. }
  71004. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71005. this._calculatedPosition.addInPlace(this.position);
  71006. }
  71007. var pose = this.rawPose;
  71008. if (poseData.orientation && pose.orientation) {
  71009. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71010. if (this._mesh) {
  71011. if (this._mesh.getScene().useRightHandedSystem) {
  71012. this._deviceRoomRotationQuaternion.z *= -1;
  71013. this._deviceRoomRotationQuaternion.w *= -1;
  71014. }
  71015. else {
  71016. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71017. }
  71018. }
  71019. // if the camera is set, rotate to the camera's rotation
  71020. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71021. }
  71022. }
  71023. };
  71024. /**
  71025. * Attaches a mesh to the controller
  71026. * @param mesh the mesh to be attached
  71027. */
  71028. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71029. if (this._mesh) {
  71030. this._mesh.parent = null;
  71031. }
  71032. this._mesh = mesh;
  71033. if (this._poseControlledCamera) {
  71034. this._mesh.parent = this._poseControlledCamera;
  71035. }
  71036. if (!this._mesh.rotationQuaternion) {
  71037. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71038. }
  71039. this._meshAttachedObservable.notifyObservers(mesh);
  71040. };
  71041. /**
  71042. * Attaches the controllers mesh to a camera
  71043. * @param camera the camera the mesh should be attached to
  71044. */
  71045. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71046. this._poseControlledCamera = camera;
  71047. if (this._mesh) {
  71048. this._mesh.parent = this._poseControlledCamera;
  71049. }
  71050. };
  71051. /**
  71052. * Disposes of the controller
  71053. */
  71054. PoseEnabledController.prototype.dispose = function () {
  71055. if (this._mesh) {
  71056. this._mesh.dispose();
  71057. }
  71058. this._mesh = null;
  71059. _super.prototype.dispose.call(this);
  71060. };
  71061. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71062. /**
  71063. * The mesh that is attached to the controller
  71064. */
  71065. get: function () {
  71066. return this._mesh;
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. /**
  71072. * Gets the ray of the controller in the direction the controller is pointing
  71073. * @param length the length the resulting ray should be
  71074. * @returns a ray in the direction the controller is pointing
  71075. */
  71076. PoseEnabledController.prototype.getForwardRay = function (length) {
  71077. if (length === void 0) { length = 100; }
  71078. if (!this.mesh) {
  71079. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71080. }
  71081. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71082. var origin = m.getTranslation();
  71083. var forward = new BABYLON.Vector3(0, 0, -1);
  71084. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71085. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71086. return new BABYLON.Ray(origin, direction, length);
  71087. };
  71088. /**
  71089. * Name of the child mesh that can be used to cast a ray from the controller
  71090. */
  71091. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71092. return PoseEnabledController;
  71093. }(BABYLON.Gamepad));
  71094. BABYLON.PoseEnabledController = PoseEnabledController;
  71095. })(BABYLON || (BABYLON = {}));
  71096. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71097. var BABYLON;
  71098. (function (BABYLON) {
  71099. /**
  71100. * Defines the WebVRController object that represents controllers tracked in 3D space
  71101. */
  71102. var WebVRController = /** @class */ (function (_super) {
  71103. __extends(WebVRController, _super);
  71104. /**
  71105. * Creates a new WebVRController from a gamepad
  71106. * @param vrGamepad the gamepad that the WebVRController should be created from
  71107. */
  71108. function WebVRController(vrGamepad) {
  71109. var _this = _super.call(this, vrGamepad) || this;
  71110. // Observables
  71111. /**
  71112. * Fired when the trigger state has changed
  71113. */
  71114. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71115. /**
  71116. * Fired when the main button state has changed
  71117. */
  71118. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71119. /**
  71120. * Fired when the secondary button state has changed
  71121. */
  71122. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71123. /**
  71124. * Fired when the pad state has changed
  71125. */
  71126. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71127. /**
  71128. * Fired when controllers stick values have changed
  71129. */
  71130. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71131. /**
  71132. * X and Y axis corrisponding to the controllers joystick
  71133. */
  71134. _this.pad = { x: 0, y: 0 };
  71135. // avoid GC, store state in a tmp object
  71136. _this._changes = {
  71137. pressChanged: false,
  71138. touchChanged: false,
  71139. valueChanged: false,
  71140. changed: false
  71141. };
  71142. _this._buttons = new Array(vrGamepad.buttons.length);
  71143. _this.hand = vrGamepad.hand;
  71144. return _this;
  71145. }
  71146. /**
  71147. * Fired when a controller button's state has changed
  71148. * @param callback the callback containing the button that was modified
  71149. */
  71150. WebVRController.prototype.onButtonStateChange = function (callback) {
  71151. this._onButtonStateChange = callback;
  71152. };
  71153. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71154. /**
  71155. * The default controller model for the controller
  71156. */
  71157. get: function () {
  71158. return this._defaultModel;
  71159. },
  71160. enumerable: true,
  71161. configurable: true
  71162. });
  71163. /**
  71164. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71165. */
  71166. WebVRController.prototype.update = function () {
  71167. _super.prototype.update.call(this);
  71168. for (var index = 0; index < this._buttons.length; index++) {
  71169. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71170. }
  71171. ;
  71172. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71173. this.pad.x = this.leftStick.x;
  71174. this.pad.y = this.leftStick.y;
  71175. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71176. }
  71177. };
  71178. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71179. if (!newState) {
  71180. newState = {
  71181. pressed: false,
  71182. touched: false,
  71183. value: 0
  71184. };
  71185. }
  71186. if (!currentState) {
  71187. this._buttons[buttonIndex] = {
  71188. pressed: newState.pressed,
  71189. touched: newState.touched,
  71190. value: newState.value
  71191. };
  71192. return;
  71193. }
  71194. this._checkChanges(newState, currentState);
  71195. if (this._changes.changed) {
  71196. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71197. this._handleButtonChange(buttonIndex, newState, this._changes);
  71198. }
  71199. this._buttons[buttonIndex].pressed = newState.pressed;
  71200. this._buttons[buttonIndex].touched = newState.touched;
  71201. // oculus triggers are never 0, thou not touched.
  71202. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71203. };
  71204. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71205. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71206. this._changes.touchChanged = newState.touched !== currentState.touched;
  71207. this._changes.valueChanged = newState.value !== currentState.value;
  71208. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71209. return this._changes;
  71210. };
  71211. /**
  71212. * Disposes of th webVRCOntroller
  71213. */
  71214. WebVRController.prototype.dispose = function () {
  71215. _super.prototype.dispose.call(this);
  71216. this.onTriggerStateChangedObservable.clear();
  71217. this.onMainButtonStateChangedObservable.clear();
  71218. this.onSecondaryButtonStateChangedObservable.clear();
  71219. this.onPadStateChangedObservable.clear();
  71220. this.onPadValuesChangedObservable.clear();
  71221. };
  71222. return WebVRController;
  71223. }(BABYLON.PoseEnabledController));
  71224. BABYLON.WebVRController = WebVRController;
  71225. })(BABYLON || (BABYLON = {}));
  71226. //# sourceMappingURL=babylon.webVRController.js.map
  71227. var BABYLON;
  71228. (function (BABYLON) {
  71229. /**
  71230. * Oculus Touch Controller
  71231. */
  71232. var OculusTouchController = /** @class */ (function (_super) {
  71233. __extends(OculusTouchController, _super);
  71234. /**
  71235. * Creates a new OculusTouchController from a gamepad
  71236. * @param vrGamepad the gamepad that the controller should be created from
  71237. */
  71238. function OculusTouchController(vrGamepad) {
  71239. var _this = _super.call(this, vrGamepad) || this;
  71240. /**
  71241. * Fired when the secondary trigger on this controller is modified
  71242. */
  71243. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71244. /**
  71245. * Fired when the thumb rest on this controller is modified
  71246. */
  71247. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71248. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71249. return _this;
  71250. }
  71251. /**
  71252. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71253. * @param scene scene in which to add meshes
  71254. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71255. */
  71256. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71257. var _this = this;
  71258. var meshName;
  71259. // Hand
  71260. if (this.hand === 'left') {
  71261. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71262. }
  71263. else { // Right is the default if no hand is specified
  71264. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71265. }
  71266. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71267. /*
  71268. Parent Mesh name: oculus_touch_left
  71269. - body
  71270. - trigger
  71271. - thumbstick
  71272. - grip
  71273. - button_y
  71274. - button_x
  71275. - button_enter
  71276. */
  71277. _this._defaultModel = newMeshes[1];
  71278. _this.attachToMesh(_this._defaultModel);
  71279. if (meshLoaded) {
  71280. meshLoaded(_this._defaultModel);
  71281. }
  71282. });
  71283. };
  71284. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71285. /**
  71286. * Fired when the A button on this controller is modified
  71287. */
  71288. get: function () {
  71289. if (this.hand === 'right') {
  71290. return this.onMainButtonStateChangedObservable;
  71291. }
  71292. else {
  71293. throw new Error('No A button on left hand');
  71294. }
  71295. },
  71296. enumerable: true,
  71297. configurable: true
  71298. });
  71299. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71300. /**
  71301. * Fired when the B button on this controller is modified
  71302. */
  71303. get: function () {
  71304. if (this.hand === 'right') {
  71305. return this.onSecondaryButtonStateChangedObservable;
  71306. }
  71307. else {
  71308. throw new Error('No B button on left hand');
  71309. }
  71310. },
  71311. enumerable: true,
  71312. configurable: true
  71313. });
  71314. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71315. /**
  71316. * Fired when the X button on this controller is modified
  71317. */
  71318. get: function () {
  71319. if (this.hand === 'left') {
  71320. return this.onMainButtonStateChangedObservable;
  71321. }
  71322. else {
  71323. throw new Error('No X button on right hand');
  71324. }
  71325. },
  71326. enumerable: true,
  71327. configurable: true
  71328. });
  71329. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71330. /**
  71331. * Fired when the Y button on this controller is modified
  71332. */
  71333. get: function () {
  71334. if (this.hand === 'left') {
  71335. return this.onSecondaryButtonStateChangedObservable;
  71336. }
  71337. else {
  71338. throw new Error('No Y button on right hand');
  71339. }
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. /**
  71345. * Called once for each button that changed state since the last frame
  71346. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71347. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71348. * 2) secondary trigger (same)
  71349. * 3) A (right) X (left), touch, pressed = value
  71350. * 4) B / Y
  71351. * 5) thumb rest
  71352. * @param buttonIdx Which button index changed
  71353. * @param state New state of the button
  71354. * @param changes Which properties on the state changed since last frame
  71355. */
  71356. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71357. var notifyObject = state; //{ state: state, changes: changes };
  71358. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71359. switch (buttonIdx) {
  71360. case 0:
  71361. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71362. return;
  71363. case 1: // index trigger
  71364. if (this._defaultModel) {
  71365. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71366. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71367. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71368. }
  71369. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71370. return;
  71371. case 2: // secondary trigger
  71372. if (this._defaultModel) {
  71373. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71374. }
  71375. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71376. return;
  71377. case 3:
  71378. if (this._defaultModel) {
  71379. if (notifyObject.pressed) {
  71380. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71381. }
  71382. else {
  71383. (this._defaultModel.getChildren()[1]).position.y = 0;
  71384. }
  71385. }
  71386. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71387. return;
  71388. case 4:
  71389. if (this._defaultModel) {
  71390. if (notifyObject.pressed) {
  71391. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71392. }
  71393. else {
  71394. (this._defaultModel.getChildren()[2]).position.y = 0;
  71395. }
  71396. }
  71397. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71398. return;
  71399. case 5:
  71400. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71401. return;
  71402. }
  71403. };
  71404. /**
  71405. * Base Url for the controller model.
  71406. */
  71407. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71408. /**
  71409. * File name for the left controller model.
  71410. */
  71411. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71412. /**
  71413. * File name for the right controller model.
  71414. */
  71415. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71416. return OculusTouchController;
  71417. }(BABYLON.WebVRController));
  71418. BABYLON.OculusTouchController = OculusTouchController;
  71419. })(BABYLON || (BABYLON = {}));
  71420. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71421. var BABYLON;
  71422. (function (BABYLON) {
  71423. /**
  71424. * Vive Controller
  71425. */
  71426. var ViveController = /** @class */ (function (_super) {
  71427. __extends(ViveController, _super);
  71428. /**
  71429. * Creates a new ViveController from a gamepad
  71430. * @param vrGamepad the gamepad that the controller should be created from
  71431. */
  71432. function ViveController(vrGamepad) {
  71433. var _this = _super.call(this, vrGamepad) || this;
  71434. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71435. _this._invertLeftStickY = true;
  71436. return _this;
  71437. }
  71438. /**
  71439. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71440. * @param scene scene in which to add meshes
  71441. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71442. */
  71443. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71444. var _this = this;
  71445. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71446. /*
  71447. Parent Mesh name: ViveWand
  71448. - body
  71449. - r_gripper
  71450. - l_gripper
  71451. - menu_button
  71452. - system_button
  71453. - trackpad
  71454. - trigger
  71455. - LED
  71456. */
  71457. _this._defaultModel = newMeshes[1];
  71458. _this.attachToMesh(_this._defaultModel);
  71459. if (meshLoaded) {
  71460. meshLoaded(_this._defaultModel);
  71461. }
  71462. });
  71463. };
  71464. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71465. /**
  71466. * Fired when the left button on this controller is modified
  71467. */
  71468. get: function () {
  71469. return this.onMainButtonStateChangedObservable;
  71470. },
  71471. enumerable: true,
  71472. configurable: true
  71473. });
  71474. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71475. /**
  71476. * Fired when the right button on this controller is modified
  71477. */
  71478. get: function () {
  71479. return this.onMainButtonStateChangedObservable;
  71480. },
  71481. enumerable: true,
  71482. configurable: true
  71483. });
  71484. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71485. /**
  71486. * Fired when the menu button on this controller is modified
  71487. */
  71488. get: function () {
  71489. return this.onSecondaryButtonStateChangedObservable;
  71490. },
  71491. enumerable: true,
  71492. configurable: true
  71493. });
  71494. /**
  71495. * Called once for each button that changed state since the last frame
  71496. * Vive mapping:
  71497. * 0: touchpad
  71498. * 1: trigger
  71499. * 2: left AND right buttons
  71500. * 3: menu button
  71501. * @param buttonIdx Which button index changed
  71502. * @param state New state of the button
  71503. * @param changes Which properties on the state changed since last frame
  71504. */
  71505. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71506. var notifyObject = state; //{ state: state, changes: changes };
  71507. switch (buttonIdx) {
  71508. case 0:
  71509. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71510. return;
  71511. case 1: // index trigger
  71512. if (this._defaultModel) {
  71513. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71514. }
  71515. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71516. return;
  71517. case 2: // left AND right button
  71518. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71519. return;
  71520. case 3:
  71521. if (this._defaultModel) {
  71522. if (notifyObject.pressed) {
  71523. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71524. }
  71525. else {
  71526. (this._defaultModel.getChildren()[2]).position.y = 0;
  71527. }
  71528. }
  71529. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71530. return;
  71531. }
  71532. };
  71533. /**
  71534. * Base Url for the controller model.
  71535. */
  71536. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71537. /**
  71538. * File name for the controller model.
  71539. */
  71540. ViveController.MODEL_FILENAME = 'wand.babylon';
  71541. return ViveController;
  71542. }(BABYLON.WebVRController));
  71543. BABYLON.ViveController = ViveController;
  71544. })(BABYLON || (BABYLON = {}));
  71545. //# sourceMappingURL=babylon.viveController.js.map
  71546. var BABYLON;
  71547. (function (BABYLON) {
  71548. /**
  71549. * Generic Controller
  71550. */
  71551. var GenericController = /** @class */ (function (_super) {
  71552. __extends(GenericController, _super);
  71553. /**
  71554. * Creates a new GenericController from a gamepad
  71555. * @param vrGamepad the gamepad that the controller should be created from
  71556. */
  71557. function GenericController(vrGamepad) {
  71558. return _super.call(this, vrGamepad) || this;
  71559. }
  71560. /**
  71561. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71562. * @param scene scene in which to add meshes
  71563. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71564. */
  71565. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71566. var _this = this;
  71567. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71568. _this._defaultModel = newMeshes[1];
  71569. _this.attachToMesh(_this._defaultModel);
  71570. if (meshLoaded) {
  71571. meshLoaded(_this._defaultModel);
  71572. }
  71573. });
  71574. };
  71575. /**
  71576. * Called once for each button that changed state since the last frame
  71577. * @param buttonIdx Which button index changed
  71578. * @param state New state of the button
  71579. * @param changes Which properties on the state changed since last frame
  71580. */
  71581. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71582. console.log("Button id: " + buttonIdx + "state: ");
  71583. console.dir(state);
  71584. };
  71585. /**
  71586. * Base Url for the controller model.
  71587. */
  71588. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71589. /**
  71590. * File name for the controller model.
  71591. */
  71592. GenericController.MODEL_FILENAME = 'generic.babylon';
  71593. return GenericController;
  71594. }(BABYLON.WebVRController));
  71595. BABYLON.GenericController = GenericController;
  71596. })(BABYLON || (BABYLON = {}));
  71597. //# sourceMappingURL=babylon.genericController.js.map
  71598. var BABYLON;
  71599. (function (BABYLON) {
  71600. /**
  71601. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71602. */
  71603. var LoadedMeshInfo = /** @class */ (function () {
  71604. function LoadedMeshInfo() {
  71605. /**
  71606. * Map of the button meshes contained in the controller
  71607. */
  71608. this.buttonMeshes = {};
  71609. /**
  71610. * Map of the axis meshes contained in the controller
  71611. */
  71612. this.axisMeshes = {};
  71613. }
  71614. return LoadedMeshInfo;
  71615. }());
  71616. /**
  71617. * Defines the WindowsMotionController object that the state of the windows motion controller
  71618. */
  71619. var WindowsMotionController = /** @class */ (function (_super) {
  71620. __extends(WindowsMotionController, _super);
  71621. /**
  71622. * Creates a new WindowsMotionController from a gamepad
  71623. * @param vrGamepad the gamepad that the controller should be created from
  71624. */
  71625. function WindowsMotionController(vrGamepad) {
  71626. var _this = _super.call(this, vrGamepad) || this;
  71627. _this._mapping = {
  71628. // Semantic button names
  71629. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71630. // A mapping of the button name to glTF model node name
  71631. // that should be transformed by button value.
  71632. buttonMeshNames: {
  71633. 'trigger': 'SELECT',
  71634. 'menu': 'MENU',
  71635. 'grip': 'GRASP',
  71636. 'thumbstick': 'THUMBSTICK_PRESS',
  71637. 'trackpad': 'TOUCHPAD_PRESS'
  71638. },
  71639. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71640. buttonObservableNames: {
  71641. 'trigger': 'onTriggerStateChangedObservable',
  71642. 'menu': 'onSecondaryButtonStateChangedObservable',
  71643. 'grip': 'onMainButtonStateChangedObservable',
  71644. 'thumbstick': 'onPadStateChangedObservable',
  71645. 'trackpad': 'onTrackpadChangedObservable'
  71646. },
  71647. // A mapping of the axis name to glTF model node name
  71648. // that should be transformed by axis value.
  71649. // This array mirrors the browserGamepad.axes array, such that
  71650. // the mesh corresponding to axis 0 is in this array index 0.
  71651. axisMeshNames: [
  71652. 'THUMBSTICK_X',
  71653. 'THUMBSTICK_Y',
  71654. 'TOUCHPAD_TOUCH_X',
  71655. 'TOUCHPAD_TOUCH_Y'
  71656. ],
  71657. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71658. };
  71659. /**
  71660. * Fired when the trackpad on this controller is clicked
  71661. */
  71662. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71663. /**
  71664. * Fired when the trackpad on this controller is modified
  71665. */
  71666. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71667. /**
  71668. * The current x and y values of this controller's trackpad
  71669. */
  71670. _this.trackpad = { x: 0, y: 0 };
  71671. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71672. _this._loadedMeshInfo = null;
  71673. return _this;
  71674. }
  71675. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71676. /**
  71677. * Fired when the trigger on this controller is modified
  71678. */
  71679. get: function () {
  71680. return this.onTriggerStateChangedObservable;
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71686. /**
  71687. * Fired when the menu button on this controller is modified
  71688. */
  71689. get: function () {
  71690. return this.onSecondaryButtonStateChangedObservable;
  71691. },
  71692. enumerable: true,
  71693. configurable: true
  71694. });
  71695. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71696. /**
  71697. * Fired when the grip button on this controller is modified
  71698. */
  71699. get: function () {
  71700. return this.onMainButtonStateChangedObservable;
  71701. },
  71702. enumerable: true,
  71703. configurable: true
  71704. });
  71705. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71706. /**
  71707. * Fired when the thumbstick button on this controller is modified
  71708. */
  71709. get: function () {
  71710. return this.onPadStateChangedObservable;
  71711. },
  71712. enumerable: true,
  71713. configurable: true
  71714. });
  71715. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71716. /**
  71717. * Fired when the touchpad button on this controller is modified
  71718. */
  71719. get: function () {
  71720. return this.onTrackpadChangedObservable;
  71721. },
  71722. enumerable: true,
  71723. configurable: true
  71724. });
  71725. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71726. /**
  71727. * Fired when the touchpad values on this controller are modified
  71728. */
  71729. get: function () {
  71730. return this.onTrackpadValuesChangedObservable;
  71731. },
  71732. enumerable: true,
  71733. configurable: true
  71734. });
  71735. /**
  71736. * Called once per frame by the engine.
  71737. */
  71738. WindowsMotionController.prototype.update = function () {
  71739. _super.prototype.update.call(this);
  71740. if (this.browserGamepad.axes) {
  71741. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71742. this.trackpad.x = this.browserGamepad["axes"][2];
  71743. this.trackpad.y = this.browserGamepad["axes"][3];
  71744. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71745. }
  71746. // Only need to animate axes if there is a loaded mesh
  71747. if (this._loadedMeshInfo) {
  71748. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71749. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71750. }
  71751. }
  71752. }
  71753. };
  71754. /**
  71755. * Called once for each button that changed state since the last frame
  71756. * @param buttonIdx Which button index changed
  71757. * @param state New state of the button
  71758. * @param changes Which properties on the state changed since last frame
  71759. */
  71760. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71761. var buttonName = this._mapping.buttons[buttonIdx];
  71762. if (!buttonName) {
  71763. return;
  71764. }
  71765. // Only emit events for buttons that we know how to map from index to name
  71766. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71767. if (observable) {
  71768. observable.notifyObservers(state);
  71769. }
  71770. this._lerpButtonTransform(buttonName, state.value);
  71771. };
  71772. /**
  71773. * Moves the buttons on the controller mesh based on their current state
  71774. * @param buttonName the name of the button to move
  71775. * @param buttonValue the value of the button which determines the buttons new position
  71776. */
  71777. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71778. // If there is no loaded mesh, there is nothing to transform.
  71779. if (!this._loadedMeshInfo) {
  71780. return;
  71781. }
  71782. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71783. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71784. return;
  71785. }
  71786. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71787. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71788. };
  71789. /**
  71790. * Moves the axis on the controller mesh based on its current state
  71791. * @param axis the index of the axis
  71792. * @param axisValue the value of the axis which determines the meshes new position
  71793. * @hidden
  71794. */
  71795. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71796. if (!this._loadedMeshInfo) {
  71797. return;
  71798. }
  71799. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71800. if (!meshInfo) {
  71801. return;
  71802. }
  71803. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71804. return;
  71805. }
  71806. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71807. var lerpValue = axisValue * 0.5 + 0.5;
  71808. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71809. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71810. };
  71811. /**
  71812. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71813. * @param scene scene in which to add meshes
  71814. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71815. */
  71816. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71817. var _this = this;
  71818. if (forceDefault === void 0) { forceDefault = false; }
  71819. var path;
  71820. var filename;
  71821. // Checking if GLB loader is present
  71822. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71823. // Determine the device specific folder based on the ID suffix
  71824. var device = 'default';
  71825. if (this.id && !forceDefault) {
  71826. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71827. device = ((match && match[0]) || device);
  71828. }
  71829. // Hand
  71830. if (this.hand === 'left') {
  71831. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71832. }
  71833. else { // Right is the default if no hand is specified
  71834. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71835. }
  71836. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71837. }
  71838. else {
  71839. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71840. path = BABYLON.GenericController.MODEL_BASE_URL;
  71841. filename = BABYLON.GenericController.MODEL_FILENAME;
  71842. }
  71843. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71844. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71845. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71846. if (!_this._loadedMeshInfo) {
  71847. return;
  71848. }
  71849. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71850. _this.attachToMesh(_this._defaultModel);
  71851. if (meshLoaded) {
  71852. meshLoaded(_this._defaultModel);
  71853. }
  71854. }, null, function (scene, message) {
  71855. BABYLON.Tools.Log(message);
  71856. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71857. if (!forceDefault) {
  71858. _this.initControllerMesh(scene, meshLoaded, true);
  71859. }
  71860. });
  71861. };
  71862. /**
  71863. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71864. * can be transformed by button presses and axes values, based on this._mapping.
  71865. *
  71866. * @param scene scene in which the meshes exist
  71867. * @param meshes list of meshes that make up the controller model to process
  71868. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71869. */
  71870. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71871. var loadedMeshInfo = null;
  71872. // Create a new mesh to contain the glTF hierarchy
  71873. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71874. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71875. var childMesh = null;
  71876. for (var i = 0; i < meshes.length; i++) {
  71877. var mesh = meshes[i];
  71878. if (!mesh.parent) {
  71879. // Exclude controller meshes from picking results
  71880. mesh.isPickable = false;
  71881. // Handle root node, attach to the new parentMesh
  71882. childMesh = mesh;
  71883. break;
  71884. }
  71885. }
  71886. if (childMesh) {
  71887. childMesh.setParent(parentMesh);
  71888. // Create our mesh info. Note that this method will always return non-null.
  71889. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71890. }
  71891. else {
  71892. BABYLON.Tools.Warn('Could not find root node in model file.');
  71893. }
  71894. return loadedMeshInfo;
  71895. };
  71896. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71897. var loadedMeshInfo = new LoadedMeshInfo();
  71898. var i;
  71899. loadedMeshInfo.rootNode = rootNode;
  71900. // Reset the caches
  71901. loadedMeshInfo.buttonMeshes = {};
  71902. loadedMeshInfo.axisMeshes = {};
  71903. // Button Meshes
  71904. for (i = 0; i < this._mapping.buttons.length; i++) {
  71905. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71906. if (!buttonMeshName) {
  71907. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71908. continue;
  71909. }
  71910. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71911. if (!buttonMesh) {
  71912. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71913. continue;
  71914. }
  71915. var buttonMeshInfo = {
  71916. index: i,
  71917. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71918. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71919. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71920. };
  71921. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71922. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71923. }
  71924. else {
  71925. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71926. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71927. '(VALUE: ' + !!buttonMeshInfo.value +
  71928. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71929. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71930. ')');
  71931. }
  71932. }
  71933. // Axis Meshes
  71934. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71935. var axisMeshName = this._mapping.axisMeshNames[i];
  71936. if (!axisMeshName) {
  71937. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71938. continue;
  71939. }
  71940. var axisMesh = getChildByName(rootNode, axisMeshName);
  71941. if (!axisMesh) {
  71942. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71943. continue;
  71944. }
  71945. var axisMeshInfo = {
  71946. index: i,
  71947. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71948. min: getImmediateChildByName(axisMesh, 'MIN'),
  71949. max: getImmediateChildByName(axisMesh, 'MAX')
  71950. };
  71951. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71952. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71953. }
  71954. else {
  71955. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71956. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71957. '(VALUE: ' + !!axisMeshInfo.value +
  71958. ', MIN: ' + !!axisMeshInfo.min +
  71959. ', MAX:' + !!axisMeshInfo.max +
  71960. ')');
  71961. }
  71962. }
  71963. // Pointing Ray
  71964. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71965. if (!loadedMeshInfo.pointingPoseNode) {
  71966. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71967. }
  71968. return loadedMeshInfo;
  71969. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71970. function getChildByName(node, name) {
  71971. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71972. }
  71973. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71974. function getImmediateChildByName(node, name) {
  71975. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71976. }
  71977. };
  71978. /**
  71979. * Gets the ray of the controller in the direction the controller is pointing
  71980. * @param length the length the resulting ray should be
  71981. * @returns a ray in the direction the controller is pointing
  71982. */
  71983. WindowsMotionController.prototype.getForwardRay = function (length) {
  71984. if (length === void 0) { length = 100; }
  71985. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71986. return _super.prototype.getForwardRay.call(this, length);
  71987. }
  71988. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71989. var origin = m.getTranslation();
  71990. var forward = new BABYLON.Vector3(0, 0, -1);
  71991. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71992. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71993. return new BABYLON.Ray(origin, direction, length);
  71994. };
  71995. /**
  71996. * Disposes of the controller
  71997. */
  71998. WindowsMotionController.prototype.dispose = function () {
  71999. _super.prototype.dispose.call(this);
  72000. this.onTrackpadChangedObservable.clear();
  72001. };
  72002. /**
  72003. * The base url used to load the left and right controller models
  72004. */
  72005. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72006. /**
  72007. * The name of the left controller model file
  72008. */
  72009. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72010. /**
  72011. * The name of the right controller model file
  72012. */
  72013. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72014. /**
  72015. * The controller name prefix for this controller type
  72016. */
  72017. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72018. /**
  72019. * The controller id pattern for this controller type
  72020. */
  72021. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72022. return WindowsMotionController;
  72023. }(BABYLON.WebVRController));
  72024. BABYLON.WindowsMotionController = WindowsMotionController;
  72025. })(BABYLON || (BABYLON = {}));
  72026. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72027. var BABYLON;
  72028. (function (BABYLON) {
  72029. /**
  72030. * Gear VR Controller
  72031. */
  72032. var GearVRController = /** @class */ (function (_super) {
  72033. __extends(GearVRController, _super);
  72034. /**
  72035. * Creates a new GearVRController from a gamepad
  72036. * @param vrGamepad the gamepad that the controller should be created from
  72037. */
  72038. function GearVRController(vrGamepad) {
  72039. var _this = _super.call(this, vrGamepad) || this;
  72040. _this._buttonIndexToObservableNameMap = [
  72041. 'onTrackpadChangedObservable',
  72042. 'onTriggerStateChangedObservable' // Trigger
  72043. ];
  72044. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72045. return _this;
  72046. }
  72047. /**
  72048. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72049. * @param scene scene in which to add meshes
  72050. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72051. */
  72052. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72053. var _this = this;
  72054. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72055. _this._defaultModel = newMeshes[1];
  72056. _this.attachToMesh(_this._defaultModel);
  72057. if (meshLoaded) {
  72058. meshLoaded(_this._defaultModel);
  72059. }
  72060. });
  72061. };
  72062. /**
  72063. * Called once for each button that changed state since the last frame
  72064. * @param buttonIdx Which button index changed
  72065. * @param state New state of the button
  72066. * @param changes Which properties on the state changed since last frame
  72067. */
  72068. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72069. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72070. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72071. // Only emit events for buttons that we know how to map from index to observable
  72072. var observable = this[observableName];
  72073. if (observable) {
  72074. observable.notifyObservers(state);
  72075. }
  72076. }
  72077. };
  72078. /**
  72079. * Base Url for the controller model.
  72080. */
  72081. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72082. /**
  72083. * File name for the controller model.
  72084. */
  72085. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72086. /**
  72087. * Gamepad Id prefix used to identify this controller.
  72088. */
  72089. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72090. return GearVRController;
  72091. }(BABYLON.WebVRController));
  72092. BABYLON.GearVRController = GearVRController;
  72093. })(BABYLON || (BABYLON = {}));
  72094. //# sourceMappingURL=babylon.gearVRController.js.map
  72095. var BABYLON;
  72096. (function (BABYLON) {
  72097. /**
  72098. * Google Daydream controller
  72099. */
  72100. var DaydreamController = /** @class */ (function (_super) {
  72101. __extends(DaydreamController, _super);
  72102. /**
  72103. * Creates a new DaydreamController from a gamepad
  72104. * @param vrGamepad the gamepad that the controller should be created from
  72105. */
  72106. function DaydreamController(vrGamepad) {
  72107. var _this = _super.call(this, vrGamepad) || this;
  72108. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72109. return _this;
  72110. }
  72111. /**
  72112. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72113. * @param scene scene in which to add meshes
  72114. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72115. */
  72116. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72117. var _this = this;
  72118. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72119. _this._defaultModel = newMeshes[1];
  72120. _this.attachToMesh(_this._defaultModel);
  72121. if (meshLoaded) {
  72122. meshLoaded(_this._defaultModel);
  72123. }
  72124. });
  72125. };
  72126. /**
  72127. * Called once for each button that changed state since the last frame
  72128. * @param buttonIdx Which button index changed
  72129. * @param state New state of the button
  72130. * @param changes Which properties on the state changed since last frame
  72131. */
  72132. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72133. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72134. if (buttonIdx === 0) {
  72135. var observable = this.onTriggerStateChangedObservable;
  72136. if (observable) {
  72137. observable.notifyObservers(state);
  72138. }
  72139. }
  72140. else {
  72141. // If the app or home buttons are ever made available
  72142. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72143. }
  72144. };
  72145. /**
  72146. * Base Url for the controller model.
  72147. */
  72148. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72149. /**
  72150. * File name for the controller model.
  72151. */
  72152. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72153. /**
  72154. * Gamepad Id prefix used to identify Daydream Controller.
  72155. */
  72156. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72157. return DaydreamController;
  72158. }(BABYLON.WebVRController));
  72159. BABYLON.DaydreamController = DaydreamController;
  72160. })(BABYLON || (BABYLON = {}));
  72161. //# sourceMappingURL=babylon.daydreamController.js.map
  72162. var BABYLON;
  72163. (function (BABYLON) {
  72164. var FollowCamera = /** @class */ (function (_super) {
  72165. __extends(FollowCamera, _super);
  72166. function FollowCamera(name, position, scene, lockedTarget) {
  72167. if (lockedTarget === void 0) { lockedTarget = null; }
  72168. var _this = _super.call(this, name, position, scene) || this;
  72169. _this.radius = 12;
  72170. _this.rotationOffset = 0;
  72171. _this.heightOffset = 4;
  72172. _this.cameraAcceleration = 0.05;
  72173. _this.maxCameraSpeed = 20;
  72174. _this.lockedTarget = lockedTarget;
  72175. return _this;
  72176. }
  72177. FollowCamera.prototype.getRadians = function (degrees) {
  72178. return degrees * Math.PI / 180;
  72179. };
  72180. FollowCamera.prototype.follow = function (cameraTarget) {
  72181. if (!cameraTarget)
  72182. return;
  72183. var yRotation;
  72184. if (cameraTarget.rotationQuaternion) {
  72185. var rotMatrix = new BABYLON.Matrix();
  72186. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72187. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72188. }
  72189. else {
  72190. yRotation = cameraTarget.rotation.y;
  72191. }
  72192. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72193. var targetPosition = cameraTarget.getAbsolutePosition();
  72194. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72195. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72196. var dx = targetX - this.position.x;
  72197. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72198. var dz = (targetZ) - this.position.z;
  72199. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72200. var vy = dy * this.cameraAcceleration;
  72201. var vz = dz * this.cameraAcceleration * 2;
  72202. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72203. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72204. }
  72205. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72206. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72207. }
  72208. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72209. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72210. }
  72211. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72212. this.setTarget(targetPosition);
  72213. };
  72214. FollowCamera.prototype._checkInputs = function () {
  72215. _super.prototype._checkInputs.call(this);
  72216. if (this.lockedTarget) {
  72217. this.follow(this.lockedTarget);
  72218. }
  72219. };
  72220. FollowCamera.prototype.getClassName = function () {
  72221. return "FollowCamera";
  72222. };
  72223. __decorate([
  72224. BABYLON.serialize()
  72225. ], FollowCamera.prototype, "radius", void 0);
  72226. __decorate([
  72227. BABYLON.serialize()
  72228. ], FollowCamera.prototype, "rotationOffset", void 0);
  72229. __decorate([
  72230. BABYLON.serialize()
  72231. ], FollowCamera.prototype, "heightOffset", void 0);
  72232. __decorate([
  72233. BABYLON.serialize()
  72234. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72235. __decorate([
  72236. BABYLON.serialize()
  72237. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72238. __decorate([
  72239. BABYLON.serializeAsMeshReference("lockedTargetId")
  72240. ], FollowCamera.prototype, "lockedTarget", void 0);
  72241. return FollowCamera;
  72242. }(BABYLON.TargetCamera));
  72243. BABYLON.FollowCamera = FollowCamera;
  72244. var ArcFollowCamera = /** @class */ (function (_super) {
  72245. __extends(ArcFollowCamera, _super);
  72246. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72247. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72248. _this.alpha = alpha;
  72249. _this.beta = beta;
  72250. _this.radius = radius;
  72251. _this.target = target;
  72252. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72253. _this.follow();
  72254. return _this;
  72255. }
  72256. ArcFollowCamera.prototype.follow = function () {
  72257. if (!this.target) {
  72258. return;
  72259. }
  72260. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72261. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72262. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72263. var targetPosition = this.target.getAbsolutePosition();
  72264. this.position = targetPosition.add(this._cartesianCoordinates);
  72265. this.setTarget(targetPosition);
  72266. };
  72267. ArcFollowCamera.prototype._checkInputs = function () {
  72268. _super.prototype._checkInputs.call(this);
  72269. this.follow();
  72270. };
  72271. ArcFollowCamera.prototype.getClassName = function () {
  72272. return "ArcFollowCamera";
  72273. };
  72274. return ArcFollowCamera;
  72275. }(BABYLON.TargetCamera));
  72276. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72277. })(BABYLON || (BABYLON = {}));
  72278. //# sourceMappingURL=babylon.followCamera.js.map
  72279. var BABYLON;
  72280. (function (BABYLON) {
  72281. // We're mainly based on the logic defined into the FreeCamera code
  72282. var UniversalCamera = /** @class */ (function (_super) {
  72283. __extends(UniversalCamera, _super);
  72284. //-- end properties for backward compatibility for inputs
  72285. function UniversalCamera(name, position, scene) {
  72286. var _this = _super.call(this, name, position, scene) || this;
  72287. _this.inputs.addGamepad();
  72288. return _this;
  72289. }
  72290. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72291. //-- Begin properties for backward compatibility for inputs
  72292. get: function () {
  72293. var gamepad = this.inputs.attached["gamepad"];
  72294. if (gamepad)
  72295. return gamepad.gamepadAngularSensibility;
  72296. return 0;
  72297. },
  72298. set: function (value) {
  72299. var gamepad = this.inputs.attached["gamepad"];
  72300. if (gamepad)
  72301. gamepad.gamepadAngularSensibility = value;
  72302. },
  72303. enumerable: true,
  72304. configurable: true
  72305. });
  72306. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72307. get: function () {
  72308. var gamepad = this.inputs.attached["gamepad"];
  72309. if (gamepad)
  72310. return gamepad.gamepadMoveSensibility;
  72311. return 0;
  72312. },
  72313. set: function (value) {
  72314. var gamepad = this.inputs.attached["gamepad"];
  72315. if (gamepad)
  72316. gamepad.gamepadMoveSensibility = value;
  72317. },
  72318. enumerable: true,
  72319. configurable: true
  72320. });
  72321. UniversalCamera.prototype.getClassName = function () {
  72322. return "UniversalCamera";
  72323. };
  72324. return UniversalCamera;
  72325. }(BABYLON.TouchCamera));
  72326. BABYLON.UniversalCamera = UniversalCamera;
  72327. })(BABYLON || (BABYLON = {}));
  72328. //# sourceMappingURL=babylon.universalCamera.js.map
  72329. var BABYLON;
  72330. (function (BABYLON) {
  72331. // We're mainly based on the logic defined into the FreeCamera code
  72332. var GamepadCamera = /** @class */ (function (_super) {
  72333. __extends(GamepadCamera, _super);
  72334. //-- end properties for backward compatibility for inputs
  72335. function GamepadCamera(name, position, scene) {
  72336. return _super.call(this, name, position, scene) || this;
  72337. }
  72338. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72339. //-- Begin properties for backward compatibility for inputs
  72340. get: function () {
  72341. var gamepad = this.inputs.attached["gamepad"];
  72342. if (gamepad)
  72343. return gamepad.gamepadAngularSensibility;
  72344. return 0;
  72345. },
  72346. set: function (value) {
  72347. var gamepad = this.inputs.attached["gamepad"];
  72348. if (gamepad)
  72349. gamepad.gamepadAngularSensibility = value;
  72350. },
  72351. enumerable: true,
  72352. configurable: true
  72353. });
  72354. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72355. get: function () {
  72356. var gamepad = this.inputs.attached["gamepad"];
  72357. if (gamepad)
  72358. return gamepad.gamepadMoveSensibility;
  72359. return 0;
  72360. },
  72361. set: function (value) {
  72362. var gamepad = this.inputs.attached["gamepad"];
  72363. if (gamepad)
  72364. gamepad.gamepadMoveSensibility = value;
  72365. },
  72366. enumerable: true,
  72367. configurable: true
  72368. });
  72369. GamepadCamera.prototype.getClassName = function () {
  72370. return "GamepadCamera";
  72371. };
  72372. return GamepadCamera;
  72373. }(BABYLON.UniversalCamera));
  72374. BABYLON.GamepadCamera = GamepadCamera;
  72375. })(BABYLON || (BABYLON = {}));
  72376. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72377. var BABYLON;
  72378. (function (BABYLON) {
  72379. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72380. function PostProcessRenderPipelineManager() {
  72381. this._renderPipelines = {};
  72382. }
  72383. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72384. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72385. };
  72386. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72387. if (unique === void 0) { unique = false; }
  72388. var renderPipeline = this._renderPipelines[renderPipelineName];
  72389. if (!renderPipeline) {
  72390. return;
  72391. }
  72392. renderPipeline._attachCameras(cameras, unique);
  72393. };
  72394. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72395. var renderPipeline = this._renderPipelines[renderPipelineName];
  72396. if (!renderPipeline) {
  72397. return;
  72398. }
  72399. renderPipeline._detachCameras(cameras);
  72400. };
  72401. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72402. var renderPipeline = this._renderPipelines[renderPipelineName];
  72403. if (!renderPipeline) {
  72404. return;
  72405. }
  72406. renderPipeline._enableEffect(renderEffectName, cameras);
  72407. };
  72408. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72409. var renderPipeline = this._renderPipelines[renderPipelineName];
  72410. if (!renderPipeline) {
  72411. return;
  72412. }
  72413. renderPipeline._disableEffect(renderEffectName, cameras);
  72414. };
  72415. PostProcessRenderPipelineManager.prototype.update = function () {
  72416. for (var renderPipelineName in this._renderPipelines) {
  72417. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72418. var pipeline = this._renderPipelines[renderPipelineName];
  72419. if (!pipeline.isSupported) {
  72420. pipeline.dispose();
  72421. delete this._renderPipelines[renderPipelineName];
  72422. }
  72423. else {
  72424. pipeline._update();
  72425. }
  72426. }
  72427. }
  72428. };
  72429. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72430. for (var renderPipelineName in this._renderPipelines) {
  72431. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72432. var pipeline = this._renderPipelines[renderPipelineName];
  72433. pipeline._rebuild();
  72434. }
  72435. }
  72436. };
  72437. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72438. for (var renderPipelineName in this._renderPipelines) {
  72439. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72440. var pipeline = this._renderPipelines[renderPipelineName];
  72441. pipeline.dispose();
  72442. }
  72443. }
  72444. };
  72445. return PostProcessRenderPipelineManager;
  72446. }());
  72447. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72448. })(BABYLON || (BABYLON = {}));
  72449. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72450. var BABYLON;
  72451. (function (BABYLON) {
  72452. /**
  72453. * This represents a set of one or more post processes in Babylon.
  72454. * A post process can be used to apply a shader to a texture after it is rendered.
  72455. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72456. */
  72457. var PostProcessRenderEffect = /** @class */ (function () {
  72458. /**
  72459. * Instantiates a post process render effect.
  72460. * A post process can be used to apply a shader to a texture after it is rendered.
  72461. * @param engine The engine the effect is tied to
  72462. * @param name The name of the effect
  72463. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72464. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72465. */
  72466. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72467. this._name = name;
  72468. this._singleInstance = singleInstance || true;
  72469. this._getPostProcesses = getPostProcesses;
  72470. this._cameras = {};
  72471. this._indicesForCamera = {};
  72472. this._postProcesses = {};
  72473. }
  72474. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72475. /**
  72476. * Checks if all the post processes in the effect are supported.
  72477. */
  72478. get: function () {
  72479. for (var index in this._postProcesses) {
  72480. if (this._postProcesses.hasOwnProperty(index)) {
  72481. var pps = this._postProcesses[index];
  72482. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72483. if (!pps[ppIndex].isSupported) {
  72484. return false;
  72485. }
  72486. }
  72487. }
  72488. }
  72489. return true;
  72490. },
  72491. enumerable: true,
  72492. configurable: true
  72493. });
  72494. /**
  72495. * Updates the current state of the effect
  72496. */
  72497. PostProcessRenderEffect.prototype._update = function () {
  72498. };
  72499. /**
  72500. * Attaches the effect on cameras
  72501. * @param cameras The camera to attach to.
  72502. */
  72503. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72504. var _this = this;
  72505. var cameraKey;
  72506. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72507. if (!cams) {
  72508. return;
  72509. }
  72510. for (var i = 0; i < cams.length; i++) {
  72511. var camera = cams[i];
  72512. var cameraName = camera.name;
  72513. if (this._singleInstance) {
  72514. cameraKey = 0;
  72515. }
  72516. else {
  72517. cameraKey = cameraName;
  72518. }
  72519. if (!this._postProcesses[cameraKey]) {
  72520. var postProcess = this._getPostProcesses();
  72521. if (postProcess) {
  72522. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72523. }
  72524. }
  72525. if (!this._indicesForCamera[cameraName]) {
  72526. this._indicesForCamera[cameraName] = [];
  72527. }
  72528. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72529. var index = camera.attachPostProcess(postProcess);
  72530. _this._indicesForCamera[cameraName].push(index);
  72531. });
  72532. if (!this._cameras[cameraName]) {
  72533. this._cameras[cameraName] = camera;
  72534. }
  72535. }
  72536. };
  72537. /**
  72538. * Detatches the effect on cameras
  72539. * @param cameras The camera to detatch from.
  72540. */
  72541. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72542. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72543. if (!cams) {
  72544. return;
  72545. }
  72546. for (var i = 0; i < cams.length; i++) {
  72547. var camera = cams[i];
  72548. var cameraName = camera.name;
  72549. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72550. camera.detachPostProcess(postProcess);
  72551. });
  72552. if (this._cameras[cameraName]) {
  72553. //this._indicesForCamera.splice(index, 1);
  72554. this._cameras[cameraName] = null;
  72555. }
  72556. }
  72557. };
  72558. /**
  72559. * Enables the effect on given cameras
  72560. * @param cameras The camera to enable.
  72561. */
  72562. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72563. var _this = this;
  72564. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72565. if (!cams) {
  72566. return;
  72567. }
  72568. for (var i = 0; i < cams.length; i++) {
  72569. var camera = cams[i];
  72570. var cameraName = camera.name;
  72571. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72572. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72573. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72574. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72575. });
  72576. }
  72577. }
  72578. }
  72579. };
  72580. /**
  72581. * Disables the effect on the given cameras
  72582. * @param cameras The camera to disable.
  72583. */
  72584. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72585. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72586. if (!cams) {
  72587. return;
  72588. }
  72589. for (var i = 0; i < cams.length; i++) {
  72590. var camera = cams[i];
  72591. var cameraName = camera.name;
  72592. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72593. camera.detachPostProcess(postProcess);
  72594. });
  72595. }
  72596. };
  72597. /**
  72598. * Gets a list of the post processes contained in the effect.
  72599. * @param camera The camera to get the post processes on.
  72600. * @returns The list of the post processes in the effect.
  72601. */
  72602. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72603. if (this._singleInstance) {
  72604. return this._postProcesses[0];
  72605. }
  72606. else {
  72607. if (!camera) {
  72608. return null;
  72609. }
  72610. return this._postProcesses[camera.name];
  72611. }
  72612. };
  72613. return PostProcessRenderEffect;
  72614. }());
  72615. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72616. })(BABYLON || (BABYLON = {}));
  72617. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72618. var BABYLON;
  72619. (function (BABYLON) {
  72620. var PostProcessRenderPipeline = /** @class */ (function () {
  72621. function PostProcessRenderPipeline(engine, name) {
  72622. this.engine = engine;
  72623. this._name = name;
  72624. this._renderEffects = {};
  72625. this._renderEffectsForIsolatedPass = new Array();
  72626. this._cameras = [];
  72627. }
  72628. PostProcessRenderPipeline.prototype.getClassName = function () {
  72629. return "PostProcessRenderPipeline";
  72630. };
  72631. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72632. get: function () {
  72633. for (var renderEffectName in this._renderEffects) {
  72634. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72635. if (!this._renderEffects[renderEffectName].isSupported) {
  72636. return false;
  72637. }
  72638. }
  72639. }
  72640. return true;
  72641. },
  72642. enumerable: true,
  72643. configurable: true
  72644. });
  72645. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72646. this._renderEffects[renderEffect._name] = renderEffect;
  72647. };
  72648. // private
  72649. PostProcessRenderPipeline.prototype._rebuild = function () {
  72650. };
  72651. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72652. var renderEffects = this._renderEffects[renderEffectName];
  72653. if (!renderEffects) {
  72654. return;
  72655. }
  72656. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72657. };
  72658. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72659. var renderEffects = this._renderEffects[renderEffectName];
  72660. if (!renderEffects) {
  72661. return;
  72662. }
  72663. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72664. };
  72665. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72666. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72667. if (!cams) {
  72668. return;
  72669. }
  72670. var indicesToDelete = [];
  72671. var i;
  72672. for (i = 0; i < cams.length; i++) {
  72673. var camera = cams[i];
  72674. var cameraName = camera.name;
  72675. if (this._cameras.indexOf(camera) === -1) {
  72676. this._cameras[cameraName] = camera;
  72677. }
  72678. else if (unique) {
  72679. indicesToDelete.push(i);
  72680. }
  72681. }
  72682. for (i = 0; i < indicesToDelete.length; i++) {
  72683. cameras.splice(indicesToDelete[i], 1);
  72684. }
  72685. for (var renderEffectName in this._renderEffects) {
  72686. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72687. this._renderEffects[renderEffectName]._attachCameras(cams);
  72688. }
  72689. }
  72690. };
  72691. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72692. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72693. if (!cams) {
  72694. return;
  72695. }
  72696. for (var renderEffectName in this._renderEffects) {
  72697. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72698. this._renderEffects[renderEffectName]._detachCameras(cams);
  72699. }
  72700. }
  72701. for (var i = 0; i < cams.length; i++) {
  72702. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72703. }
  72704. };
  72705. PostProcessRenderPipeline.prototype._update = function () {
  72706. for (var renderEffectName in this._renderEffects) {
  72707. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72708. this._renderEffects[renderEffectName]._update();
  72709. }
  72710. }
  72711. for (var i = 0; i < this._cameras.length; i++) {
  72712. var cameraName = this._cameras[i].name;
  72713. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72714. this._renderEffectsForIsolatedPass[cameraName]._update();
  72715. }
  72716. }
  72717. };
  72718. PostProcessRenderPipeline.prototype._reset = function () {
  72719. this._renderEffects = {};
  72720. this._renderEffectsForIsolatedPass = new Array();
  72721. };
  72722. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72723. // 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)
  72724. var effectKeys = Object.keys(this._renderEffects);
  72725. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72726. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72727. if (postProcesses) {
  72728. postProcesses[0].samples = sampleCount;
  72729. return true;
  72730. }
  72731. }
  72732. return false;
  72733. };
  72734. PostProcessRenderPipeline.prototype.dispose = function () {
  72735. // Must be implemented by children
  72736. };
  72737. __decorate([
  72738. BABYLON.serialize()
  72739. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72740. return PostProcessRenderPipeline;
  72741. }());
  72742. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72743. })(BABYLON || (BABYLON = {}));
  72744. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72745. var BABYLON;
  72746. (function (BABYLON) {
  72747. /**
  72748. * This represents a depth renderer in Babylon.
  72749. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72750. */
  72751. var DepthRenderer = /** @class */ (function () {
  72752. /**
  72753. * Instantiates a depth renderer
  72754. * @param scene The scene the renderer belongs to
  72755. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72756. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72757. */
  72758. function DepthRenderer(scene, type, camera) {
  72759. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72760. if (camera === void 0) { camera = null; }
  72761. var _this = this;
  72762. this._scene = scene;
  72763. this._camera = camera;
  72764. var engine = scene.getEngine();
  72765. // Render target
  72766. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72767. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72768. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72769. this._depthMap.refreshRate = 1;
  72770. this._depthMap.renderParticles = false;
  72771. this._depthMap.renderList = null;
  72772. // Camera to get depth map from to support multiple concurrent cameras
  72773. this._depthMap.activeCamera = this._camera;
  72774. this._depthMap.ignoreCameraViewport = true;
  72775. this._depthMap.useCameraPostProcesses = false;
  72776. // set default depth value to 1.0 (far away)
  72777. this._depthMap.onClearObservable.add(function (engine) {
  72778. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72779. });
  72780. // Custom render function
  72781. var renderSubMesh = function (subMesh) {
  72782. var mesh = subMesh.getRenderingMesh();
  72783. var scene = _this._scene;
  72784. var engine = scene.getEngine();
  72785. var material = subMesh.getMaterial();
  72786. if (!material) {
  72787. return;
  72788. }
  72789. // Culling and reverse (right handed system)
  72790. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72791. // Managing instances
  72792. var batch = mesh._getInstancesRenderList(subMesh._id);
  72793. if (batch.mustReturn) {
  72794. return;
  72795. }
  72796. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72797. var camera = _this._camera || scene.activeCamera;
  72798. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72799. engine.enableEffect(_this._effect);
  72800. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72801. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72802. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72803. // Alpha test
  72804. if (material && material.needAlphaTesting()) {
  72805. var alphaTexture = material.getAlphaTestTexture();
  72806. if (alphaTexture) {
  72807. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72808. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72809. }
  72810. }
  72811. // Bones
  72812. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72813. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72814. }
  72815. // Draw
  72816. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72817. }
  72818. };
  72819. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72820. var index;
  72821. if (depthOnlySubMeshes.length) {
  72822. engine.setColorWrite(false);
  72823. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72824. renderSubMesh(depthOnlySubMeshes.data[index]);
  72825. }
  72826. engine.setColorWrite(true);
  72827. }
  72828. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72829. renderSubMesh(opaqueSubMeshes.data[index]);
  72830. }
  72831. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72832. renderSubMesh(alphaTestSubMeshes.data[index]);
  72833. }
  72834. };
  72835. }
  72836. /**
  72837. * Creates the depth rendering effect and checks if the effect is ready.
  72838. * @param subMesh The submesh to be used to render the depth map of
  72839. * @param useInstances If multiple world instances should be used
  72840. * @returns if the depth renderer is ready to render the depth map
  72841. */
  72842. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72843. var material = subMesh.getMaterial();
  72844. if (material.disableDepthWrite) {
  72845. return false;
  72846. }
  72847. var defines = [];
  72848. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72849. var mesh = subMesh.getMesh();
  72850. // Alpha test
  72851. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72852. defines.push("#define ALPHATEST");
  72853. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72854. attribs.push(BABYLON.VertexBuffer.UVKind);
  72855. defines.push("#define UV1");
  72856. }
  72857. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72858. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72859. defines.push("#define UV2");
  72860. }
  72861. }
  72862. // Bones
  72863. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72864. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72865. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72866. if (mesh.numBoneInfluencers > 4) {
  72867. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72868. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72869. }
  72870. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72871. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72872. }
  72873. else {
  72874. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72875. }
  72876. // Instances
  72877. if (useInstances) {
  72878. defines.push("#define INSTANCES");
  72879. attribs.push("world0");
  72880. attribs.push("world1");
  72881. attribs.push("world2");
  72882. attribs.push("world3");
  72883. }
  72884. // Get correct effect
  72885. var join = defines.join("\n");
  72886. if (this._cachedDefines !== join) {
  72887. this._cachedDefines = join;
  72888. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72889. }
  72890. return this._effect.isReady();
  72891. };
  72892. /**
  72893. * Gets the texture which the depth map will be written to.
  72894. * @returns The depth map texture
  72895. */
  72896. DepthRenderer.prototype.getDepthMap = function () {
  72897. return this._depthMap;
  72898. };
  72899. /**
  72900. * Disposes of the depth renderer.
  72901. */
  72902. DepthRenderer.prototype.dispose = function () {
  72903. this._depthMap.dispose();
  72904. };
  72905. return DepthRenderer;
  72906. }());
  72907. BABYLON.DepthRenderer = DepthRenderer;
  72908. })(BABYLON || (BABYLON = {}));
  72909. //# sourceMappingURL=babylon.depthRenderer.js.map
  72910. var BABYLON;
  72911. (function (BABYLON) {
  72912. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72913. __extends(SSAORenderingPipeline, _super);
  72914. /**
  72915. * @constructor
  72916. * @param {string} name - The rendering pipeline name
  72917. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72918. * @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 }
  72919. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72920. */
  72921. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72922. var _this = _super.call(this, scene.getEngine(), name) || this;
  72923. // Members
  72924. /**
  72925. * The PassPostProcess id in the pipeline that contains the original scene color
  72926. */
  72927. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72928. /**
  72929. * The SSAO PostProcess id in the pipeline
  72930. */
  72931. _this.SSAORenderEffect = "SSAORenderEffect";
  72932. /**
  72933. * The horizontal blur PostProcess id in the pipeline
  72934. */
  72935. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72936. /**
  72937. * The vertical blur PostProcess id in the pipeline
  72938. */
  72939. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72940. /**
  72941. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72942. */
  72943. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72944. /**
  72945. * The output strength of the SSAO post-process. Default value is 1.0.
  72946. */
  72947. _this.totalStrength = 1.0;
  72948. /**
  72949. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72950. */
  72951. _this.radius = 0.0001;
  72952. /**
  72953. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72954. * Must not be equal to fallOff and superior to fallOff.
  72955. * Default value is 0.975
  72956. */
  72957. _this.area = 0.0075;
  72958. /**
  72959. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72960. * Must not be equal to area and inferior to area.
  72961. * Default value is 0.0
  72962. */
  72963. _this.fallOff = 0.000001;
  72964. /**
  72965. * The base color of the SSAO post-process
  72966. * The final result is "base + ssao" between [0, 1]
  72967. */
  72968. _this.base = 0.5;
  72969. _this._firstUpdate = true;
  72970. _this._scene = scene;
  72971. // Set up assets
  72972. _this._createRandomTexture();
  72973. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72974. var ssaoRatio = ratio.ssaoRatio || ratio;
  72975. var combineRatio = ratio.combineRatio || ratio;
  72976. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72977. _this._createSSAOPostProcess(ssaoRatio);
  72978. _this._createBlurPostProcess(ssaoRatio);
  72979. _this._createSSAOCombinePostProcess(combineRatio);
  72980. // Set up pipeline
  72981. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72982. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72983. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72984. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72985. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72986. // Finish
  72987. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72988. if (cameras)
  72989. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72990. return _this;
  72991. }
  72992. // Public Methods
  72993. /**
  72994. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72995. */
  72996. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72997. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72998. for (var i = 0; i < this._scene.cameras.length; i++) {
  72999. var camera = this._scene.cameras[i];
  73000. this._originalColorPostProcess.dispose(camera);
  73001. this._ssaoPostProcess.dispose(camera);
  73002. this._blurHPostProcess.dispose(camera);
  73003. this._blurVPostProcess.dispose(camera);
  73004. this._ssaoCombinePostProcess.dispose(camera);
  73005. }
  73006. this._randomTexture.dispose();
  73007. if (disableDepthRender)
  73008. this._scene.disableDepthRenderer();
  73009. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73010. _super.prototype.dispose.call(this);
  73011. };
  73012. // Private Methods
  73013. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73014. var _this = this;
  73015. var size = 16;
  73016. 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);
  73017. 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);
  73018. this._blurHPostProcess.onActivateObservable.add(function () {
  73019. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73020. _this._blurHPostProcess.kernel = size * dw;
  73021. });
  73022. this._blurVPostProcess.onActivateObservable.add(function () {
  73023. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73024. _this._blurVPostProcess.kernel = size * dw;
  73025. });
  73026. };
  73027. SSAORenderingPipeline.prototype._rebuild = function () {
  73028. this._firstUpdate = true;
  73029. _super.prototype._rebuild.call(this);
  73030. };
  73031. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73032. var _this = this;
  73033. var numSamples = 16;
  73034. var sampleSphere = [
  73035. 0.5381, 0.1856, -0.4319,
  73036. 0.1379, 0.2486, 0.4430,
  73037. 0.3371, 0.5679, -0.0057,
  73038. -0.6999, -0.0451, -0.0019,
  73039. 0.0689, -0.1598, -0.8547,
  73040. 0.0560, 0.0069, -0.1843,
  73041. -0.0146, 0.1402, 0.0762,
  73042. 0.0100, -0.1924, -0.0344,
  73043. -0.3577, -0.5301, -0.4358,
  73044. -0.3169, 0.1063, 0.0158,
  73045. 0.0103, -0.5869, 0.0046,
  73046. -0.0897, -0.4940, 0.3287,
  73047. 0.7119, -0.0154, -0.0918,
  73048. -0.0533, 0.0596, -0.5411,
  73049. 0.0352, -0.0631, 0.5460,
  73050. -0.4776, 0.2847, -0.0271
  73051. ];
  73052. var samplesFactor = 1.0 / numSamples;
  73053. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73054. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73055. "area", "fallOff", "base", "range", "viewport"
  73056. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73057. this._ssaoPostProcess.onApply = function (effect) {
  73058. if (_this._firstUpdate) {
  73059. effect.setArray3("sampleSphere", sampleSphere);
  73060. effect.setFloat("samplesFactor", samplesFactor);
  73061. effect.setFloat("randTextureTiles", 4.0);
  73062. }
  73063. effect.setFloat("totalStrength", _this.totalStrength);
  73064. effect.setFloat("radius", _this.radius);
  73065. effect.setFloat("area", _this.area);
  73066. effect.setFloat("fallOff", _this.fallOff);
  73067. effect.setFloat("base", _this.base);
  73068. effect.setTexture("textureSampler", _this._depthTexture);
  73069. effect.setTexture("randomSampler", _this._randomTexture);
  73070. };
  73071. };
  73072. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73073. var _this = this;
  73074. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73075. this._ssaoCombinePostProcess.onApply = function (effect) {
  73076. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73077. };
  73078. };
  73079. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73080. var size = 512;
  73081. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73082. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73083. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73084. var context = this._randomTexture.getContext();
  73085. var rand = function (min, max) {
  73086. return Math.random() * (max - min) + min;
  73087. };
  73088. var randVector = BABYLON.Vector3.Zero();
  73089. for (var x = 0; x < size; x++) {
  73090. for (var y = 0; y < size; y++) {
  73091. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73092. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73093. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73094. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73095. context.fillRect(x, y, 1, 1);
  73096. }
  73097. }
  73098. this._randomTexture.update(false);
  73099. };
  73100. __decorate([
  73101. BABYLON.serialize()
  73102. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73103. __decorate([
  73104. BABYLON.serialize()
  73105. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73106. __decorate([
  73107. BABYLON.serialize()
  73108. ], SSAORenderingPipeline.prototype, "area", void 0);
  73109. __decorate([
  73110. BABYLON.serialize()
  73111. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73112. __decorate([
  73113. BABYLON.serialize()
  73114. ], SSAORenderingPipeline.prototype, "base", void 0);
  73115. return SSAORenderingPipeline;
  73116. }(BABYLON.PostProcessRenderPipeline));
  73117. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73118. })(BABYLON || (BABYLON = {}));
  73119. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73120. var BABYLON;
  73121. (function (BABYLON) {
  73122. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73123. __extends(SSAO2RenderingPipeline, _super);
  73124. /**
  73125. * @constructor
  73126. * @param {string} name - The rendering pipeline name
  73127. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73128. * @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 }
  73129. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73130. */
  73131. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73132. var _this = _super.call(this, scene.getEngine(), name) || this;
  73133. // Members
  73134. /**
  73135. * The PassPostProcess id in the pipeline that contains the original scene color
  73136. */
  73137. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73138. /**
  73139. * The SSAO PostProcess id in the pipeline
  73140. */
  73141. _this.SSAORenderEffect = "SSAORenderEffect";
  73142. /**
  73143. * The horizontal blur PostProcess id in the pipeline
  73144. */
  73145. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73146. /**
  73147. * The vertical blur PostProcess id in the pipeline
  73148. */
  73149. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73150. /**
  73151. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73152. */
  73153. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73154. /**
  73155. * The output strength of the SSAO post-process. Default value is 1.0.
  73156. */
  73157. _this.totalStrength = 1.0;
  73158. /**
  73159. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73160. */
  73161. _this.maxZ = 100.0;
  73162. /**
  73163. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73164. */
  73165. _this.minZAspect = 0.2;
  73166. /**
  73167. * Number of samples used for the SSAO calculations. Default value is 8
  73168. */
  73169. _this._samples = 8;
  73170. /**
  73171. * Are we using bilateral blur ?
  73172. */
  73173. _this._expensiveBlur = true;
  73174. /**
  73175. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73176. */
  73177. _this.radius = 2.0;
  73178. /**
  73179. * The base color of the SSAO post-process
  73180. * The final result is "base + ssao" between [0, 1]
  73181. */
  73182. _this.base = 0.1;
  73183. _this._firstUpdate = true;
  73184. _this._scene = scene;
  73185. _this._ratio = ratio;
  73186. if (!_this.isSupported) {
  73187. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73188. return _this;
  73189. }
  73190. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73191. var blurRatio = _this._ratio.blurRatio || ratio;
  73192. // Set up assets
  73193. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73194. _this._createRandomTexture();
  73195. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73196. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73197. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73198. _this._createSSAOPostProcess(1.0);
  73199. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73200. _this._createSSAOCombinePostProcess(blurRatio);
  73201. // Set up pipeline
  73202. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73203. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73204. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73205. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73206. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73207. // Finish
  73208. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73209. if (cameras)
  73210. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73211. return _this;
  73212. }
  73213. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73214. get: function () {
  73215. return this._samples;
  73216. },
  73217. set: function (n) {
  73218. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73219. this._samples = n;
  73220. this._sampleSphere = this._generateHemisphere();
  73221. this._firstUpdate = true;
  73222. },
  73223. enumerable: true,
  73224. configurable: true
  73225. });
  73226. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73227. get: function () {
  73228. return this._expensiveBlur;
  73229. },
  73230. set: function (b) {
  73231. 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"]);
  73232. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73233. this._expensiveBlur = b;
  73234. this._firstUpdate = true;
  73235. },
  73236. enumerable: true,
  73237. configurable: true
  73238. });
  73239. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73240. /**
  73241. * Support test.
  73242. */
  73243. get: function () {
  73244. var engine = BABYLON.Engine.LastCreatedEngine;
  73245. if (!engine) {
  73246. return false;
  73247. }
  73248. return engine.getCaps().drawBuffersExtension;
  73249. },
  73250. enumerable: true,
  73251. configurable: true
  73252. });
  73253. // Public Methods
  73254. /**
  73255. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73256. */
  73257. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73258. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73259. for (var i = 0; i < this._scene.cameras.length; i++) {
  73260. var camera = this._scene.cameras[i];
  73261. this._originalColorPostProcess.dispose(camera);
  73262. this._ssaoPostProcess.dispose(camera);
  73263. this._blurHPostProcess.dispose(camera);
  73264. this._blurVPostProcess.dispose(camera);
  73265. this._ssaoCombinePostProcess.dispose(camera);
  73266. }
  73267. this._randomTexture.dispose();
  73268. if (disableGeometryBufferRenderer)
  73269. this._scene.disableGeometryBufferRenderer();
  73270. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73271. _super.prototype.dispose.call(this);
  73272. };
  73273. // Private Methods
  73274. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73275. var _this = this;
  73276. this._samplerOffsets = [];
  73277. var expensive = this.expensiveBlur;
  73278. for (var i = -8; i < 8; i++) {
  73279. this._samplerOffsets.push(i * 2 + 0.5);
  73280. }
  73281. 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");
  73282. this._blurHPostProcess.onApply = function (effect) {
  73283. if (!_this._scene.activeCamera) {
  73284. return;
  73285. }
  73286. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73287. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73288. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73289. effect.setFloat("radius", _this.radius);
  73290. effect.setTexture("depthSampler", _this._depthTexture);
  73291. if (_this._firstUpdate) {
  73292. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73293. }
  73294. };
  73295. 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");
  73296. this._blurVPostProcess.onApply = function (effect) {
  73297. if (!_this._scene.activeCamera) {
  73298. return;
  73299. }
  73300. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73301. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73302. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73303. effect.setFloat("radius", _this.radius);
  73304. effect.setTexture("depthSampler", _this._depthTexture);
  73305. if (_this._firstUpdate) {
  73306. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73307. _this._firstUpdate = false;
  73308. }
  73309. };
  73310. };
  73311. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73312. this._firstUpdate = true;
  73313. _super.prototype._rebuild.call(this);
  73314. };
  73315. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73316. var numSamples = this.samples;
  73317. var result = [];
  73318. var vector, scale;
  73319. var rand = function (min, max) {
  73320. return Math.random() * (max - min) + min;
  73321. };
  73322. var i = 0;
  73323. while (i < numSamples) {
  73324. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73325. vector.normalize();
  73326. scale = i / numSamples;
  73327. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73328. vector.scaleInPlace(scale);
  73329. result.push(vector.x, vector.y, vector.z);
  73330. i++;
  73331. }
  73332. return result;
  73333. };
  73334. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73335. var _this = this;
  73336. var numSamples = this.samples;
  73337. this._sampleSphere = this._generateHemisphere();
  73338. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73339. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73340. "base", "range", "projection", "near", "far", "texelSize",
  73341. "xViewport", "yViewport", "maxZ", "minZAspect"
  73342. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73343. this._ssaoPostProcess.onApply = function (effect) {
  73344. if (_this._firstUpdate) {
  73345. effect.setArray3("sampleSphere", _this._sampleSphere);
  73346. effect.setFloat("randTextureTiles", 4.0);
  73347. }
  73348. if (!_this._scene.activeCamera) {
  73349. return;
  73350. }
  73351. effect.setFloat("samplesFactor", 1 / _this.samples);
  73352. effect.setFloat("totalStrength", _this.totalStrength);
  73353. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73354. effect.setFloat("radius", _this.radius);
  73355. effect.setFloat("maxZ", _this.maxZ);
  73356. effect.setFloat("minZAspect", _this.minZAspect);
  73357. effect.setFloat("base", _this.base);
  73358. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73359. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73360. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73361. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73362. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73363. effect.setTexture("textureSampler", _this._depthTexture);
  73364. effect.setTexture("normalSampler", _this._normalTexture);
  73365. effect.setTexture("randomSampler", _this._randomTexture);
  73366. };
  73367. };
  73368. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73369. var _this = this;
  73370. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73371. this._ssaoCombinePostProcess.onApply = function (effect) {
  73372. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73373. };
  73374. };
  73375. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73376. var size = 512;
  73377. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73378. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73379. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73380. var context = this._randomTexture.getContext();
  73381. var rand = function (min, max) {
  73382. return Math.random() * (max - min) + min;
  73383. };
  73384. var randVector = BABYLON.Vector3.Zero();
  73385. for (var x = 0; x < size; x++) {
  73386. for (var y = 0; y < size; y++) {
  73387. randVector.x = rand(0.0, 1.0);
  73388. randVector.y = rand(0.0, 1.0);
  73389. randVector.z = 0.0;
  73390. randVector.normalize();
  73391. randVector.scaleInPlace(255);
  73392. randVector.x = Math.floor(randVector.x);
  73393. randVector.y = Math.floor(randVector.y);
  73394. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73395. context.fillRect(x, y, 1, 1);
  73396. }
  73397. }
  73398. this._randomTexture.update(false);
  73399. };
  73400. /**
  73401. * Serialize the rendering pipeline (Used when exporting)
  73402. * @returns the serialized object
  73403. */
  73404. SSAO2RenderingPipeline.prototype.serialize = function () {
  73405. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73406. serializationObject.customType = "SSAO2RenderingPipeline";
  73407. return serializationObject;
  73408. };
  73409. /**
  73410. * Parse the serialized pipeline
  73411. * @param source Source pipeline.
  73412. * @param scene The scene to load the pipeline to.
  73413. * @param rootUrl The URL of the serialized pipeline.
  73414. * @returns An instantiated pipeline from the serialized object.
  73415. */
  73416. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73417. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73418. };
  73419. __decorate([
  73420. BABYLON.serialize()
  73421. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73422. __decorate([
  73423. BABYLON.serialize()
  73424. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73425. __decorate([
  73426. BABYLON.serialize()
  73427. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73428. __decorate([
  73429. BABYLON.serialize("samples")
  73430. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73431. __decorate([
  73432. BABYLON.serialize()
  73433. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73434. __decorate([
  73435. BABYLON.serialize("expensiveBlur")
  73436. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73437. __decorate([
  73438. BABYLON.serialize()
  73439. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73440. __decorate([
  73441. BABYLON.serialize()
  73442. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73443. return SSAO2RenderingPipeline;
  73444. }(BABYLON.PostProcessRenderPipeline));
  73445. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73446. })(BABYLON || (BABYLON = {}));
  73447. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73448. // BABYLON.JS Chromatic Aberration GLSL Shader
  73449. // Author: Olivier Guyot
  73450. // Separates very slightly R, G and B colors on the edges of the screen
  73451. // Inspired by Francois Tarlier & Martins Upitis
  73452. var BABYLON;
  73453. (function (BABYLON) {
  73454. var LensRenderingPipeline = /** @class */ (function (_super) {
  73455. __extends(LensRenderingPipeline, _super);
  73456. /**
  73457. * @constructor
  73458. *
  73459. * Effect parameters are as follow:
  73460. * {
  73461. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73462. * edge_blur: number; // from 0 to x (1 for realism)
  73463. * distortion: number; // from 0 to x (1 for realism)
  73464. * grain_amount: number; // from 0 to 1
  73465. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73466. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73467. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73468. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73469. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73470. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73471. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73472. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73473. * }
  73474. * Note: if an effect parameter is unset, effect is disabled
  73475. *
  73476. * @param {string} name - The rendering pipeline name
  73477. * @param {object} parameters - An object containing all parameters (see above)
  73478. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73479. * @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)
  73480. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73481. */
  73482. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73483. if (ratio === void 0) { ratio = 1.0; }
  73484. var _this = _super.call(this, scene.getEngine(), name) || this;
  73485. // Lens effects can be of the following:
  73486. // - chromatic aberration (slight shift of RGB colors)
  73487. // - blur on the edge of the lens
  73488. // - lens distortion
  73489. // - depth-of-field blur & highlights enhancing
  73490. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73491. // - grain effect (noise or custom texture)
  73492. // Two additional texture samplers are needed:
  73493. // - depth map (for depth-of-field)
  73494. // - grain texture
  73495. /**
  73496. * The chromatic aberration PostProcess id in the pipeline
  73497. */
  73498. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73499. /**
  73500. * The highlights enhancing PostProcess id in the pipeline
  73501. */
  73502. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73503. /**
  73504. * The depth-of-field PostProcess id in the pipeline
  73505. */
  73506. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73507. _this._scene = scene;
  73508. // Fetch texture samplers
  73509. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73510. if (parameters.grain_texture) {
  73511. _this._grainTexture = parameters.grain_texture;
  73512. }
  73513. else {
  73514. _this._createGrainTexture();
  73515. }
  73516. // save parameters
  73517. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73518. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73519. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73520. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73521. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73522. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73523. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73524. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73525. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73526. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73527. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73528. // Create effects
  73529. _this._createChromaticAberrationPostProcess(ratio);
  73530. _this._createHighlightsPostProcess(ratio);
  73531. _this._createDepthOfFieldPostProcess(ratio / 4);
  73532. // Set up pipeline
  73533. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73534. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73535. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73536. if (_this._highlightsGain === -1) {
  73537. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73538. }
  73539. // Finish
  73540. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73541. if (cameras) {
  73542. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73543. }
  73544. return _this;
  73545. }
  73546. // public methods (self explanatory)
  73547. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73548. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73549. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73550. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73551. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73552. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73553. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73554. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73555. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73556. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73557. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73558. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73559. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73560. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73561. };
  73562. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73563. this._highlightsPostProcess.updateEffect();
  73564. };
  73565. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73566. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73567. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73568. this._highlightsGain = amount;
  73569. };
  73570. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73571. if (this._highlightsGain === -1) {
  73572. this._highlightsGain = 1.0;
  73573. }
  73574. this._highlightsThreshold = amount;
  73575. };
  73576. LensRenderingPipeline.prototype.disableHighlights = function () {
  73577. this._highlightsGain = -1;
  73578. };
  73579. /**
  73580. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73581. */
  73582. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73583. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73584. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73585. this._chromaticAberrationPostProcess = null;
  73586. this._highlightsPostProcess = null;
  73587. this._depthOfFieldPostProcess = null;
  73588. this._grainTexture.dispose();
  73589. if (disableDepthRender)
  73590. this._scene.disableDepthRenderer();
  73591. };
  73592. // colors shifting and distortion
  73593. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73594. var _this = this;
  73595. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73596. [], // samplers
  73597. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73598. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73599. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73600. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73601. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73602. effect.setFloat('radialIntensity', 1);
  73603. effect.setFloat2('direction', 17, 17);
  73604. effect.setFloat2('centerPosition', 0.5, 0.5);
  73605. };
  73606. };
  73607. // highlights enhancing
  73608. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73609. var _this = this;
  73610. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73611. [], // samplers
  73612. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73613. this._highlightsPostProcess.onApply = function (effect) {
  73614. effect.setFloat('gain', _this._highlightsGain);
  73615. effect.setFloat('threshold', _this._highlightsThreshold);
  73616. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73617. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73618. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73619. };
  73620. };
  73621. // colors shifting and distortion
  73622. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73623. var _this = this;
  73624. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73625. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73626. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73627. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73628. this._depthOfFieldPostProcess.onApply = function (effect) {
  73629. effect.setTexture("depthSampler", _this._depthTexture);
  73630. effect.setTexture("grainSampler", _this._grainTexture);
  73631. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73632. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73633. effect.setFloat('grain_amount', _this._grainAmount);
  73634. effect.setBool('blur_noise', _this._blurNoise);
  73635. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73636. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73637. effect.setFloat('distortion', _this._distortion);
  73638. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73639. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73640. effect.setFloat('aperture', _this._dofAperture);
  73641. effect.setFloat('darken', _this._dofDarken);
  73642. effect.setFloat('edge_blur', _this._edgeBlur);
  73643. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73644. if (_this._scene.activeCamera) {
  73645. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73646. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73647. }
  73648. };
  73649. };
  73650. // creates a black and white random noise texture, 512x512
  73651. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73652. var size = 512;
  73653. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73654. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73655. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73656. var context = this._grainTexture.getContext();
  73657. var rand = function (min, max) {
  73658. return Math.random() * (max - min) + min;
  73659. };
  73660. var value;
  73661. for (var x = 0; x < size; x++) {
  73662. for (var y = 0; y < size; y++) {
  73663. value = Math.floor(rand(0.42, 0.58) * 255);
  73664. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73665. context.fillRect(x, y, 1, 1);
  73666. }
  73667. }
  73668. this._grainTexture.update(false);
  73669. };
  73670. return LensRenderingPipeline;
  73671. }(BABYLON.PostProcessRenderPipeline));
  73672. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73673. })(BABYLON || (BABYLON = {}));
  73674. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73675. var BABYLON;
  73676. (function (BABYLON) {
  73677. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73678. __extends(StandardRenderingPipeline, _super);
  73679. /**
  73680. * @constructor
  73681. * @param {string} name - The rendering pipeline name
  73682. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73683. * @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)
  73684. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73685. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73686. */
  73687. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73688. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73689. var _this = _super.call(this, scene.getEngine(), name) || this;
  73690. _this.downSampleX4PostProcess = null;
  73691. _this.brightPassPostProcess = null;
  73692. _this.blurHPostProcesses = [];
  73693. _this.blurVPostProcesses = [];
  73694. _this.textureAdderPostProcess = null;
  73695. _this.volumetricLightPostProcess = null;
  73696. _this.volumetricLightSmoothXPostProcess = null;
  73697. _this.volumetricLightSmoothYPostProcess = null;
  73698. _this.volumetricLightMergePostProces = null;
  73699. _this.volumetricLightFinalPostProcess = null;
  73700. _this.luminancePostProcess = null;
  73701. _this.luminanceDownSamplePostProcesses = [];
  73702. _this.hdrPostProcess = null;
  73703. _this.textureAdderFinalPostProcess = null;
  73704. _this.lensFlareFinalPostProcess = null;
  73705. _this.hdrFinalPostProcess = null;
  73706. _this.lensFlarePostProcess = null;
  73707. _this.lensFlareComposePostProcess = null;
  73708. _this.motionBlurPostProcess = null;
  73709. _this.depthOfFieldPostProcess = null;
  73710. // Values
  73711. _this.brightThreshold = 1.0;
  73712. _this.blurWidth = 512.0;
  73713. _this.horizontalBlur = false;
  73714. _this.exposure = 1.0;
  73715. _this.lensTexture = null;
  73716. _this.volumetricLightCoefficient = 0.2;
  73717. _this.volumetricLightPower = 4.0;
  73718. _this.volumetricLightBlurScale = 64.0;
  73719. _this.sourceLight = null;
  73720. _this.hdrMinimumLuminance = 1.0;
  73721. _this.hdrDecreaseRate = 0.5;
  73722. _this.hdrIncreaseRate = 0.5;
  73723. _this.lensColorTexture = null;
  73724. _this.lensFlareStrength = 20.0;
  73725. _this.lensFlareGhostDispersal = 1.4;
  73726. _this.lensFlareHaloWidth = 0.7;
  73727. _this.lensFlareDistortionStrength = 16.0;
  73728. _this.lensStarTexture = null;
  73729. _this.lensFlareDirtTexture = null;
  73730. _this.depthOfFieldDistance = 10.0;
  73731. _this.depthOfFieldBlurWidth = 64.0;
  73732. _this.motionStrength = 1.0;
  73733. // IAnimatable
  73734. _this.animations = [];
  73735. _this._currentDepthOfFieldSource = null;
  73736. _this._hdrCurrentLuminance = 1.0;
  73737. // Getters and setters
  73738. _this._bloomEnabled = true;
  73739. _this._depthOfFieldEnabled = false;
  73740. _this._vlsEnabled = false;
  73741. _this._lensFlareEnabled = false;
  73742. _this._hdrEnabled = false;
  73743. _this._motionBlurEnabled = false;
  73744. _this._motionBlurSamples = 64.0;
  73745. _this._volumetricLightStepsCount = 50.0;
  73746. _this._cameras = cameras || [];
  73747. // Initialize
  73748. _this._scene = scene;
  73749. _this._basePostProcess = originalPostProcess;
  73750. _this._ratio = ratio;
  73751. // Misc
  73752. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73753. // Finish
  73754. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73755. _this._buildPipeline();
  73756. return _this;
  73757. }
  73758. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73759. get: function () {
  73760. return this._bloomEnabled;
  73761. },
  73762. set: function (enabled) {
  73763. if (this._bloomEnabled === enabled) {
  73764. return;
  73765. }
  73766. this._bloomEnabled = enabled;
  73767. this._buildPipeline();
  73768. },
  73769. enumerable: true,
  73770. configurable: true
  73771. });
  73772. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73773. get: function () {
  73774. return this._depthOfFieldEnabled;
  73775. },
  73776. set: function (enabled) {
  73777. if (this._depthOfFieldEnabled === enabled) {
  73778. return;
  73779. }
  73780. this._depthOfFieldEnabled = enabled;
  73781. this._buildPipeline();
  73782. },
  73783. enumerable: true,
  73784. configurable: true
  73785. });
  73786. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73787. get: function () {
  73788. return this._lensFlareEnabled;
  73789. },
  73790. set: function (enabled) {
  73791. if (this._lensFlareEnabled === enabled) {
  73792. return;
  73793. }
  73794. this._lensFlareEnabled = enabled;
  73795. this._buildPipeline();
  73796. },
  73797. enumerable: true,
  73798. configurable: true
  73799. });
  73800. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73801. get: function () {
  73802. return this._hdrEnabled;
  73803. },
  73804. set: function (enabled) {
  73805. if (this._hdrEnabled === enabled) {
  73806. return;
  73807. }
  73808. this._hdrEnabled = enabled;
  73809. this._buildPipeline();
  73810. },
  73811. enumerable: true,
  73812. configurable: true
  73813. });
  73814. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73815. get: function () {
  73816. return this._vlsEnabled;
  73817. },
  73818. set: function (enabled) {
  73819. if (this._vlsEnabled === enabled) {
  73820. return;
  73821. }
  73822. if (enabled) {
  73823. var geometry = this._scene.enableGeometryBufferRenderer();
  73824. if (!geometry) {
  73825. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73826. return;
  73827. }
  73828. }
  73829. this._vlsEnabled = enabled;
  73830. this._buildPipeline();
  73831. },
  73832. enumerable: true,
  73833. configurable: true
  73834. });
  73835. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73836. get: function () {
  73837. return this._motionBlurEnabled;
  73838. },
  73839. set: function (enabled) {
  73840. if (this._motionBlurEnabled === enabled) {
  73841. return;
  73842. }
  73843. this._motionBlurEnabled = enabled;
  73844. this._buildPipeline();
  73845. },
  73846. enumerable: true,
  73847. configurable: true
  73848. });
  73849. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73850. get: function () {
  73851. return this._volumetricLightStepsCount;
  73852. },
  73853. set: function (count) {
  73854. if (this.volumetricLightPostProcess) {
  73855. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73856. }
  73857. this._volumetricLightStepsCount = count;
  73858. },
  73859. enumerable: true,
  73860. configurable: true
  73861. });
  73862. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73863. get: function () {
  73864. return this._motionBlurSamples;
  73865. },
  73866. set: function (samples) {
  73867. if (this.motionBlurPostProcess) {
  73868. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73869. }
  73870. this._motionBlurSamples = samples;
  73871. },
  73872. enumerable: true,
  73873. configurable: true
  73874. });
  73875. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73876. var _this = this;
  73877. var ratio = this._ratio;
  73878. var scene = this._scene;
  73879. this._disposePostProcesses();
  73880. this._reset();
  73881. // Create pass post-process
  73882. if (!this._basePostProcess) {
  73883. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73884. this.originalPostProcess.onApply = function (effect) {
  73885. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73886. };
  73887. }
  73888. else {
  73889. this.originalPostProcess = this._basePostProcess;
  73890. }
  73891. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73892. this._currentDepthOfFieldSource = this.originalPostProcess;
  73893. if (this._bloomEnabled) {
  73894. // Create down sample X4 post-process
  73895. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73896. // Create bright pass post-process
  73897. this._createBrightPassPostProcess(scene, ratio / 2);
  73898. // Create gaussian blur post-processes (down sampling blurs)
  73899. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73900. // Create texture adder post-process
  73901. this._createTextureAdderPostProcess(scene, ratio);
  73902. // Create depth-of-field source post-process
  73903. 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);
  73904. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73905. }
  73906. if (this._vlsEnabled) {
  73907. // Create volumetric light
  73908. this._createVolumetricLightPostProcess(scene, ratio);
  73909. // Create volumetric light final post-process
  73910. 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);
  73911. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73912. }
  73913. if (this._lensFlareEnabled) {
  73914. // Create lens flare post-process
  73915. this._createLensFlarePostProcess(scene, ratio);
  73916. // Create depth-of-field source post-process post lens-flare and disable it now
  73917. 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);
  73918. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73919. }
  73920. if (this._hdrEnabled) {
  73921. // Create luminance
  73922. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73923. // Create HDR
  73924. this._createHdrPostProcess(scene, ratio);
  73925. // Create depth-of-field source post-process post hdr and disable it now
  73926. 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);
  73927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73928. }
  73929. if (this._depthOfFieldEnabled) {
  73930. // Create gaussian blur used by depth-of-field
  73931. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73932. // Create depth-of-field post-process
  73933. this._createDepthOfFieldPostProcess(scene, ratio);
  73934. }
  73935. if (this._motionBlurEnabled) {
  73936. // Create motion blur post-process
  73937. this._createMotionBlurPostProcess(scene, ratio);
  73938. }
  73939. if (this._cameras !== null) {
  73940. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73941. }
  73942. };
  73943. // Down Sample X4 Post-Processs
  73944. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73945. var _this = this;
  73946. var downSampleX4Offsets = new Array(32);
  73947. 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);
  73948. this.downSampleX4PostProcess.onApply = function (effect) {
  73949. var id = 0;
  73950. var width = _this.downSampleX4PostProcess.width;
  73951. var height = _this.downSampleX4PostProcess.height;
  73952. for (var i = -2; i < 2; i++) {
  73953. for (var j = -2; j < 2; j++) {
  73954. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73955. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73956. id += 2;
  73957. }
  73958. }
  73959. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73960. };
  73961. // Add to pipeline
  73962. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73963. };
  73964. // Brightpass Post-Process
  73965. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73966. var _this = this;
  73967. var brightOffsets = new Array(8);
  73968. 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);
  73969. this.brightPassPostProcess.onApply = function (effect) {
  73970. var sU = (1.0 / _this.brightPassPostProcess.width);
  73971. var sV = (1.0 / _this.brightPassPostProcess.height);
  73972. brightOffsets[0] = -0.5 * sU;
  73973. brightOffsets[1] = 0.5 * sV;
  73974. brightOffsets[2] = 0.5 * sU;
  73975. brightOffsets[3] = 0.5 * sV;
  73976. brightOffsets[4] = -0.5 * sU;
  73977. brightOffsets[5] = -0.5 * sV;
  73978. brightOffsets[6] = 0.5 * sU;
  73979. brightOffsets[7] = -0.5 * sV;
  73980. effect.setArray2("dsOffsets", brightOffsets);
  73981. effect.setFloat("brightThreshold", _this.brightThreshold);
  73982. };
  73983. // Add to pipeline
  73984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73985. };
  73986. // Create blur H&V post-processes
  73987. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73988. var _this = this;
  73989. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73990. var engine = scene.getEngine();
  73991. 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);
  73992. 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);
  73993. blurX.onActivateObservable.add(function () {
  73994. var dw = blurX.width / engine.getRenderWidth();
  73995. blurX.kernel = _this[blurWidthKey] * dw;
  73996. });
  73997. blurY.onActivateObservable.add(function () {
  73998. var dw = blurY.height / engine.getRenderHeight();
  73999. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74000. });
  74001. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74003. this.blurHPostProcesses.push(blurX);
  74004. this.blurVPostProcesses.push(blurY);
  74005. };
  74006. // Create texture adder post-process
  74007. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74008. var _this = this;
  74009. 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);
  74010. this.textureAdderPostProcess.onApply = function (effect) {
  74011. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74012. effect.setTexture("lensSampler", _this.lensTexture);
  74013. effect.setFloat("exposure", _this.exposure);
  74014. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74015. };
  74016. // Add to pipeline
  74017. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74018. };
  74019. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74020. var _this = this;
  74021. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74022. geometryRenderer.enablePosition = true;
  74023. var geometry = geometryRenderer.getGBuffer();
  74024. // Base post-process
  74025. 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));
  74026. var depthValues = BABYLON.Vector2.Zero();
  74027. this.volumetricLightPostProcess.onApply = function (effect) {
  74028. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74029. var generator = _this.sourceLight.getShadowGenerator();
  74030. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74031. effect.setTexture("positionSampler", geometry.textures[2]);
  74032. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74033. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74034. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74035. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74036. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74037. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74038. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74039. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74040. effect.setVector2("depthValues", depthValues);
  74041. }
  74042. };
  74043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74044. // Smooth
  74045. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74046. // Merge
  74047. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74048. this.volumetricLightMergePostProces.onApply = function (effect) {
  74049. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74050. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74051. };
  74052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74053. };
  74054. // Create luminance
  74055. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74056. var _this = this;
  74057. // Create luminance
  74058. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74059. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74060. var offsets = [];
  74061. this.luminancePostProcess.onApply = function (effect) {
  74062. var sU = (1.0 / _this.luminancePostProcess.width);
  74063. var sV = (1.0 / _this.luminancePostProcess.height);
  74064. offsets[0] = -0.5 * sU;
  74065. offsets[1] = 0.5 * sV;
  74066. offsets[2] = 0.5 * sU;
  74067. offsets[3] = 0.5 * sV;
  74068. offsets[4] = -0.5 * sU;
  74069. offsets[5] = -0.5 * sV;
  74070. offsets[6] = 0.5 * sU;
  74071. offsets[7] = -0.5 * sV;
  74072. effect.setArray2("lumOffsets", offsets);
  74073. };
  74074. // Add to pipeline
  74075. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74076. // Create down sample luminance
  74077. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74078. var size = Math.pow(3, i);
  74079. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74080. if (i === 0) {
  74081. defines += "#define FINAL_DOWN_SAMPLER";
  74082. }
  74083. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74084. this.luminanceDownSamplePostProcesses.push(postProcess);
  74085. }
  74086. // Create callbacks and add effects
  74087. var lastLuminance = this.luminancePostProcess;
  74088. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74089. var downSampleOffsets = new Array(18);
  74090. pp.onApply = function (effect) {
  74091. if (!lastLuminance) {
  74092. return;
  74093. }
  74094. var id = 0;
  74095. for (var x = -1; x < 2; x++) {
  74096. for (var y = -1; y < 2; y++) {
  74097. downSampleOffsets[id] = x / lastLuminance.width;
  74098. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74099. id += 2;
  74100. }
  74101. }
  74102. effect.setArray2("dsOffsets", downSampleOffsets);
  74103. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74104. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74105. lastLuminance = _this.luminancePostProcess;
  74106. }
  74107. else {
  74108. lastLuminance = pp;
  74109. }
  74110. };
  74111. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74112. pp.onAfterRender = function (effect) {
  74113. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74114. 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);
  74115. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74116. };
  74117. }
  74118. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74119. });
  74120. };
  74121. // Create HDR post-process
  74122. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74123. var _this = this;
  74124. 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);
  74125. var outputLiminance = 1;
  74126. var time = 0;
  74127. var lastTime = 0;
  74128. this.hdrPostProcess.onApply = function (effect) {
  74129. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74130. time += scene.getEngine().getDeltaTime();
  74131. if (outputLiminance < 0) {
  74132. outputLiminance = _this._hdrCurrentLuminance;
  74133. }
  74134. else {
  74135. var dt = (lastTime - time) / 1000.0;
  74136. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74137. outputLiminance += _this.hdrDecreaseRate * dt;
  74138. }
  74139. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74140. outputLiminance -= _this.hdrIncreaseRate * dt;
  74141. }
  74142. else {
  74143. outputLiminance = _this._hdrCurrentLuminance;
  74144. }
  74145. }
  74146. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74147. effect.setFloat("averageLuminance", outputLiminance);
  74148. lastTime = time;
  74149. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74150. };
  74151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74152. };
  74153. // Create lens flare post-process
  74154. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74155. var _this = this;
  74156. 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);
  74157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74158. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74159. 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);
  74160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74161. var resolution = new BABYLON.Vector2(0, 0);
  74162. // Lens flare
  74163. this.lensFlarePostProcess.onApply = function (effect) {
  74164. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74165. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74166. effect.setFloat("strength", _this.lensFlareStrength);
  74167. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74168. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74169. // Shift
  74170. resolution.x = _this.lensFlarePostProcess.width;
  74171. resolution.y = _this.lensFlarePostProcess.height;
  74172. effect.setVector2("resolution", resolution);
  74173. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74174. };
  74175. // Compose
  74176. 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);
  74177. 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);
  74178. this.lensFlareComposePostProcess.onApply = function (effect) {
  74179. if (!_this._scene.activeCamera) {
  74180. return;
  74181. }
  74182. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74183. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74184. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74185. // Lens start rotation matrix
  74186. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74187. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74188. 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));
  74189. camRot *= 4.0;
  74190. 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);
  74191. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74192. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74193. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74194. };
  74195. };
  74196. // Create depth-of-field post-process
  74197. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74198. var _this = this;
  74199. 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);
  74200. this.depthOfFieldPostProcess.onApply = function (effect) {
  74201. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74202. effect.setTexture("depthSampler", _this._getDepthTexture());
  74203. effect.setFloat("distance", _this.depthOfFieldDistance);
  74204. };
  74205. // Add to pipeline
  74206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74207. };
  74208. // Create motion blur post-process
  74209. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74210. var _this = this;
  74211. 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);
  74212. var motionScale = 0;
  74213. var prevViewProjection = BABYLON.Matrix.Identity();
  74214. var invViewProjection = BABYLON.Matrix.Identity();
  74215. var viewProjection = BABYLON.Matrix.Identity();
  74216. var screenSize = BABYLON.Vector2.Zero();
  74217. this.motionBlurPostProcess.onApply = function (effect) {
  74218. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74219. viewProjection.invertToRef(invViewProjection);
  74220. effect.setMatrix("inverseViewProjection", invViewProjection);
  74221. effect.setMatrix("prevViewProjection", prevViewProjection);
  74222. prevViewProjection = viewProjection;
  74223. screenSize.x = _this.motionBlurPostProcess.width;
  74224. screenSize.y = _this.motionBlurPostProcess.height;
  74225. effect.setVector2("screenSize", screenSize);
  74226. motionScale = scene.getEngine().getFps() / 60.0;
  74227. effect.setFloat("motionScale", motionScale);
  74228. effect.setFloat("motionStrength", _this.motionStrength);
  74229. effect.setTexture("depthSampler", _this._getDepthTexture());
  74230. };
  74231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74232. };
  74233. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74234. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74235. var renderer = this._scene.enableGeometryBufferRenderer();
  74236. return renderer.getGBuffer().textures[0];
  74237. }
  74238. return this._scene.enableDepthRenderer().getDepthMap();
  74239. };
  74240. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74241. for (var i = 0; i < this._cameras.length; i++) {
  74242. var camera = this._cameras[i];
  74243. if (this.originalPostProcess) {
  74244. this.originalPostProcess.dispose(camera);
  74245. }
  74246. if (this.downSampleX4PostProcess) {
  74247. this.downSampleX4PostProcess.dispose(camera);
  74248. }
  74249. if (this.brightPassPostProcess) {
  74250. this.brightPassPostProcess.dispose(camera);
  74251. }
  74252. if (this.textureAdderPostProcess) {
  74253. this.textureAdderPostProcess.dispose(camera);
  74254. }
  74255. if (this.textureAdderFinalPostProcess) {
  74256. this.textureAdderFinalPostProcess.dispose(camera);
  74257. }
  74258. if (this.volumetricLightPostProcess) {
  74259. this.volumetricLightPostProcess.dispose(camera);
  74260. }
  74261. if (this.volumetricLightSmoothXPostProcess) {
  74262. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74263. }
  74264. if (this.volumetricLightSmoothYPostProcess) {
  74265. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74266. }
  74267. if (this.volumetricLightMergePostProces) {
  74268. this.volumetricLightMergePostProces.dispose(camera);
  74269. }
  74270. if (this.volumetricLightFinalPostProcess) {
  74271. this.volumetricLightFinalPostProcess.dispose(camera);
  74272. }
  74273. if (this.lensFlarePostProcess) {
  74274. this.lensFlarePostProcess.dispose(camera);
  74275. }
  74276. if (this.lensFlareComposePostProcess) {
  74277. this.lensFlareComposePostProcess.dispose(camera);
  74278. }
  74279. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74280. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74281. }
  74282. if (this.luminancePostProcess) {
  74283. this.luminancePostProcess.dispose(camera);
  74284. }
  74285. if (this.hdrPostProcess) {
  74286. this.hdrPostProcess.dispose(camera);
  74287. }
  74288. if (this.hdrFinalPostProcess) {
  74289. this.hdrFinalPostProcess.dispose(camera);
  74290. }
  74291. if (this.depthOfFieldPostProcess) {
  74292. this.depthOfFieldPostProcess.dispose(camera);
  74293. }
  74294. if (this.motionBlurPostProcess) {
  74295. this.motionBlurPostProcess.dispose(camera);
  74296. }
  74297. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74298. this.blurHPostProcesses[j].dispose(camera);
  74299. }
  74300. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74301. this.blurVPostProcesses[j].dispose(camera);
  74302. }
  74303. }
  74304. this.originalPostProcess = null;
  74305. this.downSampleX4PostProcess = null;
  74306. this.brightPassPostProcess = null;
  74307. this.textureAdderPostProcess = null;
  74308. this.textureAdderFinalPostProcess = null;
  74309. this.volumetricLightPostProcess = null;
  74310. this.volumetricLightSmoothXPostProcess = null;
  74311. this.volumetricLightSmoothYPostProcess = null;
  74312. this.volumetricLightMergePostProces = null;
  74313. this.volumetricLightFinalPostProcess = null;
  74314. this.lensFlarePostProcess = null;
  74315. this.lensFlareComposePostProcess = null;
  74316. this.luminancePostProcess = null;
  74317. this.hdrPostProcess = null;
  74318. this.hdrFinalPostProcess = null;
  74319. this.depthOfFieldPostProcess = null;
  74320. this.motionBlurPostProcess = null;
  74321. this.luminanceDownSamplePostProcesses = [];
  74322. this.blurHPostProcesses = [];
  74323. this.blurVPostProcesses = [];
  74324. };
  74325. /**
  74326. * Dispose of the pipeline and stop all post processes
  74327. */
  74328. StandardRenderingPipeline.prototype.dispose = function () {
  74329. this._disposePostProcesses();
  74330. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74331. _super.prototype.dispose.call(this);
  74332. };
  74333. /**
  74334. * Serialize the rendering pipeline (Used when exporting)
  74335. * @returns the serialized object
  74336. */
  74337. StandardRenderingPipeline.prototype.serialize = function () {
  74338. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74339. if (this.sourceLight) {
  74340. serializationObject.sourceLightId = this.sourceLight.id;
  74341. }
  74342. serializationObject.customType = "StandardRenderingPipeline";
  74343. return serializationObject;
  74344. };
  74345. /**
  74346. * Parse the serialized pipeline
  74347. * @param source Source pipeline.
  74348. * @param scene The scene to load the pipeline to.
  74349. * @param rootUrl The URL of the serialized pipeline.
  74350. * @returns An instantiated pipeline from the serialized object.
  74351. */
  74352. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74353. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74354. if (source.sourceLightId) {
  74355. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74356. }
  74357. return p;
  74358. };
  74359. // Luminance steps
  74360. StandardRenderingPipeline.LuminanceSteps = 6;
  74361. __decorate([
  74362. BABYLON.serialize()
  74363. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74364. __decorate([
  74365. BABYLON.serialize()
  74366. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74367. __decorate([
  74368. BABYLON.serialize()
  74369. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74370. __decorate([
  74371. BABYLON.serialize()
  74372. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74373. __decorate([
  74374. BABYLON.serializeAsTexture("lensTexture")
  74375. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74376. __decorate([
  74377. BABYLON.serialize()
  74378. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74379. __decorate([
  74380. BABYLON.serialize()
  74381. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74382. __decorate([
  74383. BABYLON.serialize()
  74384. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74385. __decorate([
  74386. BABYLON.serialize()
  74387. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74388. __decorate([
  74389. BABYLON.serialize()
  74390. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74391. __decorate([
  74392. BABYLON.serialize()
  74393. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74394. __decorate([
  74395. BABYLON.serializeAsTexture("lensColorTexture")
  74396. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74397. __decorate([
  74398. BABYLON.serialize()
  74399. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74400. __decorate([
  74401. BABYLON.serialize()
  74402. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74403. __decorate([
  74404. BABYLON.serialize()
  74405. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74406. __decorate([
  74407. BABYLON.serialize()
  74408. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74409. __decorate([
  74410. BABYLON.serializeAsTexture("lensStarTexture")
  74411. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74412. __decorate([
  74413. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74414. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74415. __decorate([
  74416. BABYLON.serialize()
  74417. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74418. __decorate([
  74419. BABYLON.serialize()
  74420. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74421. __decorate([
  74422. BABYLON.serialize()
  74423. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74424. __decorate([
  74425. BABYLON.serialize()
  74426. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74427. __decorate([
  74428. BABYLON.serialize()
  74429. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74430. __decorate([
  74431. BABYLON.serialize()
  74432. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74433. __decorate([
  74434. BABYLON.serialize()
  74435. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74436. __decorate([
  74437. BABYLON.serialize()
  74438. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74439. __decorate([
  74440. BABYLON.serialize()
  74441. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74442. __decorate([
  74443. BABYLON.serialize()
  74444. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74445. __decorate([
  74446. BABYLON.serialize()
  74447. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74448. __decorate([
  74449. BABYLON.serialize()
  74450. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74451. return StandardRenderingPipeline;
  74452. }(BABYLON.PostProcessRenderPipeline));
  74453. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74454. })(BABYLON || (BABYLON = {}));
  74455. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74456. var BABYLON;
  74457. (function (BABYLON) {
  74458. var FxaaPostProcess = /** @class */ (function (_super) {
  74459. __extends(FxaaPostProcess, _super);
  74460. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74461. if (camera === void 0) { camera = null; }
  74462. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74463. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74464. var defines = _this._getDefines();
  74465. _this.updateEffect(defines);
  74466. _this.onApplyObservable.add(function (effect) {
  74467. var texelSize = _this.texelSize;
  74468. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74469. });
  74470. return _this;
  74471. }
  74472. FxaaPostProcess.prototype._getDefines = function () {
  74473. var engine = this.getEngine();
  74474. if (!engine) {
  74475. return null;
  74476. }
  74477. var glInfo = engine.getGlInfo();
  74478. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74479. return "#define MALI 1\n";
  74480. }
  74481. return null;
  74482. };
  74483. return FxaaPostProcess;
  74484. }(BABYLON.PostProcess));
  74485. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74486. })(BABYLON || (BABYLON = {}));
  74487. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74488. var BABYLON;
  74489. (function (BABYLON) {
  74490. /**
  74491. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74492. */
  74493. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74494. __extends(ChromaticAberrationPostProcess, _super);
  74495. /**
  74496. * Creates a new instance ChromaticAberrationPostProcess
  74497. * @param name The name of the effect.
  74498. * @param screenWidth The width of the screen to apply the effect on.
  74499. * @param screenHeight The height of the screen to apply the effect on.
  74500. * @param options The required width/height ratio to downsize to before computing the render pass.
  74501. * @param camera The camera to apply the render pass to.
  74502. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74503. * @param engine The engine which the post process will be applied. (default: current engine)
  74504. * @param reusable If the post process can be reused on the same frame. (default: false)
  74505. * @param textureType Type of textures used when performing the post process. (default: 0)
  74506. * @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)
  74507. */
  74508. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74509. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74510. if (blockCompilation === void 0) { blockCompilation = false; }
  74511. 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;
  74512. /**
  74513. * The amount of seperation of rgb channels (default: 30)
  74514. */
  74515. _this.aberrationAmount = 30;
  74516. /**
  74517. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74518. */
  74519. _this.radialIntensity = 0;
  74520. /**
  74521. * 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))
  74522. */
  74523. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74524. /**
  74525. * 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))
  74526. */
  74527. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74528. _this.onApplyObservable.add(function (effect) {
  74529. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74530. effect.setFloat('screen_width', screenWidth);
  74531. effect.setFloat('screen_height', screenHeight);
  74532. effect.setFloat('radialIntensity', _this.radialIntensity);
  74533. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74534. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74535. });
  74536. return _this;
  74537. }
  74538. return ChromaticAberrationPostProcess;
  74539. }(BABYLON.PostProcess));
  74540. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74541. })(BABYLON || (BABYLON = {}));
  74542. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74543. var BABYLON;
  74544. (function (BABYLON) {
  74545. /**
  74546. * The GrainPostProcess adds noise to the image at mid luminance levels
  74547. */
  74548. var GrainPostProcess = /** @class */ (function (_super) {
  74549. __extends(GrainPostProcess, _super);
  74550. /**
  74551. * Creates a new instance of @see GrainPostProcess
  74552. * @param name The name of the effect.
  74553. * @param options The required width/height ratio to downsize to before computing the render pass.
  74554. * @param camera The camera to apply the render pass to.
  74555. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74556. * @param engine The engine which the post process will be applied. (default: current engine)
  74557. * @param reusable If the post process can be reused on the same frame. (default: false)
  74558. * @param textureType Type of textures used when performing the post process. (default: 0)
  74559. * @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)
  74560. */
  74561. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74562. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74563. if (blockCompilation === void 0) { blockCompilation = false; }
  74564. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74565. /**
  74566. * The intensity of the grain added (default: 30)
  74567. */
  74568. _this.intensity = 30;
  74569. /**
  74570. * If the grain should be randomized on every frame
  74571. */
  74572. _this.animated = false;
  74573. _this.onApplyObservable.add(function (effect) {
  74574. effect.setFloat('intensity', _this.intensity);
  74575. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74576. });
  74577. return _this;
  74578. }
  74579. return GrainPostProcess;
  74580. }(BABYLON.PostProcess));
  74581. BABYLON.GrainPostProcess = GrainPostProcess;
  74582. })(BABYLON || (BABYLON = {}));
  74583. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74584. var BABYLON;
  74585. (function (BABYLON) {
  74586. /**
  74587. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74588. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74589. */
  74590. var SharpenPostProcess = /** @class */ (function (_super) {
  74591. __extends(SharpenPostProcess, _super);
  74592. /**
  74593. * Creates a new instance ConvolutionPostProcess
  74594. * @param name The name of the effect.
  74595. * @param options The required width/height ratio to downsize to before computing the render pass.
  74596. * @param camera The camera to apply the render pass to.
  74597. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74598. * @param engine The engine which the post process will be applied. (default: current engine)
  74599. * @param reusable If the post process can be reused on the same frame. (default: false)
  74600. * @param textureType Type of textures used when performing the post process. (default: 0)
  74601. * @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)
  74602. */
  74603. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74604. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74605. if (blockCompilation === void 0) { blockCompilation = false; }
  74606. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74607. /**
  74608. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74609. */
  74610. _this.colorAmount = 1.0;
  74611. /**
  74612. * How much sharpness should be applied (default: 0.3)
  74613. */
  74614. _this.edgeAmount = 0.3;
  74615. _this.onApply = function (effect) {
  74616. effect.setFloat2("screenSize", _this.width, _this.height);
  74617. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74618. };
  74619. return _this;
  74620. }
  74621. return SharpenPostProcess;
  74622. }(BABYLON.PostProcess));
  74623. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74624. })(BABYLON || (BABYLON = {}));
  74625. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74626. var BABYLON;
  74627. (function (BABYLON) {
  74628. /**
  74629. * The Blur Post Process which blurs an image based on a kernel and direction.
  74630. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74631. */
  74632. var BlurPostProcess = /** @class */ (function (_super) {
  74633. __extends(BlurPostProcess, _super);
  74634. /**
  74635. * Creates a new instance BlurPostProcess
  74636. * @param name The name of the effect.
  74637. * @param direction The direction in which to blur the image.
  74638. * @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.
  74639. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74640. * @param camera The camera to apply the render pass to.
  74641. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74642. * @param engine The engine which the post process will be applied. (default: current engine)
  74643. * @param reusable If the post process can be reused on the same frame. (default: false)
  74644. * @param textureType Type of textures used when performing the post process. (default: 0)
  74645. * @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)
  74646. */
  74647. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74649. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74650. if (defines === void 0) { defines = ""; }
  74651. if (blockCompilation === void 0) { blockCompilation = false; }
  74652. 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;
  74653. _this.direction = direction;
  74654. _this.blockCompilation = blockCompilation;
  74655. _this._packedFloat = false;
  74656. _this._staticDefines = "";
  74657. _this._staticDefines = defines;
  74658. _this.onApplyObservable.add(function (effect) {
  74659. if (_this._outputTexture) {
  74660. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74661. }
  74662. else {
  74663. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74664. }
  74665. });
  74666. _this.kernel = kernel;
  74667. return _this;
  74668. }
  74669. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74670. /**
  74671. * Gets the length in pixels of the blur sample region
  74672. */
  74673. get: function () {
  74674. return this._idealKernel;
  74675. },
  74676. /**
  74677. * Sets the length in pixels of the blur sample region
  74678. */
  74679. set: function (v) {
  74680. if (this._idealKernel === v) {
  74681. return;
  74682. }
  74683. v = Math.max(v, 1);
  74684. this._idealKernel = v;
  74685. this._kernel = this._nearestBestKernel(v);
  74686. if (!this.blockCompilation) {
  74687. this._updateParameters();
  74688. }
  74689. },
  74690. enumerable: true,
  74691. configurable: true
  74692. });
  74693. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74694. /**
  74695. * Gets wether or not the blur is unpacking/repacking floats
  74696. */
  74697. get: function () {
  74698. return this._packedFloat;
  74699. },
  74700. /**
  74701. * Sets wether or not the blur needs to unpack/repack floats
  74702. */
  74703. set: function (v) {
  74704. if (this._packedFloat === v) {
  74705. return;
  74706. }
  74707. this._packedFloat = v;
  74708. if (!this.blockCompilation) {
  74709. this._updateParameters();
  74710. }
  74711. },
  74712. enumerable: true,
  74713. configurable: true
  74714. });
  74715. /**
  74716. * Updates the effect with the current post process compile time values and recompiles the shader.
  74717. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74718. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74719. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74720. * @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
  74721. * @param onCompiled Called when the shader has been compiled.
  74722. * @param onError Called if there is an error when compiling a shader.
  74723. */
  74724. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74725. if (defines === void 0) { defines = null; }
  74726. if (uniforms === void 0) { uniforms = null; }
  74727. if (samplers === void 0) { samplers = null; }
  74728. this._updateParameters(onCompiled, onError);
  74729. };
  74730. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74731. // Generate sampling offsets and weights
  74732. var N = this._kernel;
  74733. var centerIndex = (N - 1) / 2;
  74734. // Generate Gaussian sampling weights over kernel
  74735. var offsets = [];
  74736. var weights = [];
  74737. var totalWeight = 0;
  74738. for (var i = 0; i < N; i++) {
  74739. var u = i / (N - 1);
  74740. var w = this._gaussianWeight(u * 2.0 - 1);
  74741. offsets[i] = (i - centerIndex);
  74742. weights[i] = w;
  74743. totalWeight += w;
  74744. }
  74745. // Normalize weights
  74746. for (var i = 0; i < weights.length; i++) {
  74747. weights[i] /= totalWeight;
  74748. }
  74749. // Optimize: combine samples to take advantage of hardware linear sampling
  74750. // Walk from left to center, combining pairs (symmetrically)
  74751. var linearSamplingWeights = [];
  74752. var linearSamplingOffsets = [];
  74753. var linearSamplingMap = [];
  74754. for (var i = 0; i <= centerIndex; i += 2) {
  74755. var j = Math.min(i + 1, Math.floor(centerIndex));
  74756. var singleCenterSample = i === j;
  74757. if (singleCenterSample) {
  74758. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74759. }
  74760. else {
  74761. var sharedCell = j === centerIndex;
  74762. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74763. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74764. if (offsetLinear === 0) {
  74765. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74766. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74767. }
  74768. else {
  74769. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74770. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74771. }
  74772. }
  74773. }
  74774. for (var i = 0; i < linearSamplingMap.length; i++) {
  74775. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74776. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74777. }
  74778. // Replace with optimized
  74779. offsets = linearSamplingOffsets;
  74780. weights = linearSamplingWeights;
  74781. // Generate shaders
  74782. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74783. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74784. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74785. var defines = "";
  74786. defines += this._staticDefines;
  74787. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74788. if (this._staticDefines.indexOf("DOF") != -1) {
  74789. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74790. varyingCount--;
  74791. }
  74792. for (var i = 0; i < varyingCount; i++) {
  74793. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74794. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74795. }
  74796. var depCount = 0;
  74797. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74798. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74799. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74800. depCount++;
  74801. }
  74802. if (this.packedFloat) {
  74803. defines += "#define PACKEDFLOAT 1";
  74804. }
  74805. this.blockCompilation = false;
  74806. _super.prototype.updateEffect.call(this, defines, null, null, {
  74807. varyingCount: varyingCount,
  74808. depCount: depCount
  74809. }, onCompiled, onError);
  74810. };
  74811. /**
  74812. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74813. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74814. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74815. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74816. * The gaps between physical kernels are compensated for in the weighting of the samples
  74817. * @param idealKernel Ideal blur kernel.
  74818. * @return Nearest best kernel.
  74819. */
  74820. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74821. var v = Math.round(idealKernel);
  74822. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74823. var k = _a[_i];
  74824. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74825. return Math.max(k, 3);
  74826. }
  74827. }
  74828. return Math.max(v, 3);
  74829. };
  74830. /**
  74831. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74832. * @param x The point on the Gaussian distribution to sample.
  74833. * @return the value of the Gaussian function at x.
  74834. */
  74835. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74836. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74837. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74838. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74839. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74840. // truncated at around 1.3% of peak strength.
  74841. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74842. var sigma = (1 / 3);
  74843. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74844. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74845. var weight = (1.0 / denominator) * Math.exp(exponent);
  74846. return weight;
  74847. };
  74848. /**
  74849. * Generates a string that can be used as a floating point number in GLSL.
  74850. * @param x Value to print.
  74851. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74852. * @return GLSL float string.
  74853. */
  74854. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74855. if (decimalFigures === void 0) { decimalFigures = 8; }
  74856. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74857. };
  74858. return BlurPostProcess;
  74859. }(BABYLON.PostProcess));
  74860. BABYLON.BlurPostProcess = BlurPostProcess;
  74861. })(BABYLON || (BABYLON = {}));
  74862. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74863. var BABYLON;
  74864. (function (BABYLON) {
  74865. /**
  74866. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74867. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74868. * based on samples that have a large difference in distance than the center pixel.
  74869. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74870. */
  74871. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74872. __extends(DepthOfFieldBlurPostProcess, _super);
  74873. /**
  74874. * Creates a new instance CircleOfConfusionPostProcess
  74875. * @param name The name of the effect.
  74876. * @param scene The scene the effect belongs to.
  74877. * @param direction The direction the blur should be applied.
  74878. * @param kernel The size of the kernel used to blur.
  74879. * @param options The required width/height ratio to downsize to before computing the render pass.
  74880. * @param camera The camera to apply the render pass to.
  74881. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74882. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74883. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74884. * @param engine The engine which the post process will be applied. (default: current engine)
  74885. * @param reusable If the post process can be reused on the same frame. (default: false)
  74886. * @param textureType Type of textures used when performing the post process. (default: 0)
  74887. * @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)
  74888. */
  74889. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74890. if (imageToBlur === void 0) { imageToBlur = null; }
  74891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74892. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74893. if (blockCompilation === void 0) { blockCompilation = false; }
  74894. 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;
  74895. _this.direction = direction;
  74896. _this.onApplyObservable.add(function (effect) {
  74897. if (imageToBlur != null) {
  74898. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74899. }
  74900. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74901. if (scene.activeCamera) {
  74902. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74903. }
  74904. });
  74905. return _this;
  74906. }
  74907. return DepthOfFieldBlurPostProcess;
  74908. }(BABYLON.BlurPostProcess));
  74909. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74910. })(BABYLON || (BABYLON = {}));
  74911. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74912. var BABYLON;
  74913. (function (BABYLON) {
  74914. /**
  74915. * Options to be set when merging outputs from the default pipeline.
  74916. */
  74917. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74918. function DepthOfFieldMergePostProcessOptions() {
  74919. }
  74920. return DepthOfFieldMergePostProcessOptions;
  74921. }());
  74922. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74923. /**
  74924. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74925. */
  74926. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74927. __extends(DepthOfFieldMergePostProcess, _super);
  74928. /**
  74929. * Creates a new instance of DepthOfFieldMergePostProcess
  74930. * @param name The name of the effect.
  74931. * @param originalFromInput Post process which's input will be used for the merge.
  74932. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74933. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74934. * @param options The required width/height ratio to downsize to before computing the render pass.
  74935. * @param camera The camera to apply the render pass to.
  74936. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74937. * @param engine The engine which the post process will be applied. (default: current engine)
  74938. * @param reusable If the post process can be reused on the same frame. (default: false)
  74939. * @param textureType Type of textures used when performing the post process. (default: 0)
  74940. * @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)
  74941. */
  74942. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74943. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74944. if (blockCompilation === void 0) { blockCompilation = false; }
  74945. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74946. _this.blurSteps = blurSteps;
  74947. _this.onApplyObservable.add(function (effect) {
  74948. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74949. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74950. blurSteps.forEach(function (step, index) {
  74951. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74952. });
  74953. });
  74954. if (!blockCompilation) {
  74955. _this.updateEffect();
  74956. }
  74957. return _this;
  74958. }
  74959. /**
  74960. * Updates the effect with the current post process compile time values and recompiles the shader.
  74961. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74962. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74963. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74964. * @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
  74965. * @param onCompiled Called when the shader has been compiled.
  74966. * @param onError Called if there is an error when compiling a shader.
  74967. */
  74968. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74969. if (defines === void 0) { defines = null; }
  74970. if (uniforms === void 0) { uniforms = null; }
  74971. if (samplers === void 0) { samplers = null; }
  74972. if (!defines) {
  74973. defines = "";
  74974. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74975. }
  74976. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74977. };
  74978. return DepthOfFieldMergePostProcess;
  74979. }(BABYLON.PostProcess));
  74980. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74981. })(BABYLON || (BABYLON = {}));
  74982. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74983. var BABYLON;
  74984. (function (BABYLON) {
  74985. /**
  74986. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74987. */
  74988. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74989. __extends(CircleOfConfusionPostProcess, _super);
  74990. /**
  74991. * Creates a new instance CircleOfConfusionPostProcess
  74992. * @param name The name of the effect.
  74993. * @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.
  74994. * @param options The required width/height ratio to downsize to before computing the render pass.
  74995. * @param camera The camera to apply the render pass to.
  74996. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74997. * @param engine The engine which the post process will be applied. (default: current engine)
  74998. * @param reusable If the post process can be reused on the same frame. (default: false)
  74999. * @param textureType Type of textures used when performing the post process. (default: 0)
  75000. * @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)
  75001. */
  75002. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75003. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75004. if (blockCompilation === void 0) { blockCompilation = false; }
  75005. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75006. /**
  75007. * 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.
  75008. */
  75009. _this.lensSize = 50;
  75010. /**
  75011. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75012. */
  75013. _this.fStop = 1.4;
  75014. /**
  75015. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75016. */
  75017. _this.focusDistance = 2000;
  75018. /**
  75019. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75020. */
  75021. _this.focalLength = 50;
  75022. _this._depthTexture = null;
  75023. _this._depthTexture = depthTexture;
  75024. _this.onApplyObservable.add(function (effect) {
  75025. if (!_this._depthTexture) {
  75026. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75027. return;
  75028. }
  75029. effect.setTexture("depthSampler", _this._depthTexture);
  75030. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75031. var aperture = _this.lensSize / _this.fStop;
  75032. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75033. effect.setFloat('focusDistance', _this.focusDistance);
  75034. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75035. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75036. });
  75037. return _this;
  75038. }
  75039. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75040. /**
  75041. * 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.
  75042. */
  75043. set: function (value) {
  75044. this._depthTexture = value;
  75045. },
  75046. enumerable: true,
  75047. configurable: true
  75048. });
  75049. return CircleOfConfusionPostProcess;
  75050. }(BABYLON.PostProcess));
  75051. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75052. })(BABYLON || (BABYLON = {}));
  75053. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75054. var BABYLON;
  75055. (function (BABYLON) {
  75056. /**
  75057. * Specifies the level of max blur that should be applied when using the depth of field effect
  75058. */
  75059. var DepthOfFieldEffectBlurLevel;
  75060. (function (DepthOfFieldEffectBlurLevel) {
  75061. /**
  75062. * Subtle blur
  75063. */
  75064. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75065. /**
  75066. * Medium blur
  75067. */
  75068. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75069. /**
  75070. * Large blur
  75071. */
  75072. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75073. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75074. ;
  75075. /**
  75076. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75077. */
  75078. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75079. __extends(DepthOfFieldEffect, _super);
  75080. /**
  75081. * Creates a new instance DepthOfFieldEffect
  75082. * @param scene The scene the effect belongs to.
  75083. * @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.
  75084. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75085. * @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)
  75086. */
  75087. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75088. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75089. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75090. if (blockCompilation === void 0) { blockCompilation = false; }
  75091. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75092. return _this._effects;
  75093. }, true) || this;
  75094. /**
  75095. * Internal post processes in depth of field effect
  75096. */
  75097. _this._effects = [];
  75098. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75099. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75100. // 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)
  75101. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75102. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75103. _this._depthOfFieldBlurY = [];
  75104. _this._depthOfFieldBlurX = [];
  75105. var blurCount = 1;
  75106. var kernelSize = 15;
  75107. switch (blurLevel) {
  75108. case DepthOfFieldEffectBlurLevel.High: {
  75109. blurCount = 3;
  75110. kernelSize = 51;
  75111. break;
  75112. }
  75113. case DepthOfFieldEffectBlurLevel.Medium: {
  75114. blurCount = 2;
  75115. kernelSize = 31;
  75116. break;
  75117. }
  75118. default: {
  75119. kernelSize = 15;
  75120. blurCount = 1;
  75121. break;
  75122. }
  75123. }
  75124. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75125. var ratio = 1.0;
  75126. for (var i = 0; i < blurCount; i++) {
  75127. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75128. blurY.autoClear = false;
  75129. ratio = 0.75 / Math.pow(2, i);
  75130. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75131. blurX.autoClear = false;
  75132. _this._depthOfFieldBlurY.push(blurY);
  75133. _this._depthOfFieldBlurX.push(blurX);
  75134. }
  75135. // Set all post processes on the effect.
  75136. _this._effects = [_this._circleOfConfusion];
  75137. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75138. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75139. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75140. }
  75141. // Merge blurred images with original image based on circleOfConfusion
  75142. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75143. _this._dofMerge.autoClear = false;
  75144. _this._effects.push(_this._dofMerge);
  75145. return _this;
  75146. }
  75147. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75148. get: function () {
  75149. return this._circleOfConfusion.focalLength;
  75150. },
  75151. /**
  75152. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75153. */
  75154. set: function (value) {
  75155. this._circleOfConfusion.focalLength = value;
  75156. },
  75157. enumerable: true,
  75158. configurable: true
  75159. });
  75160. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75161. get: function () {
  75162. return this._circleOfConfusion.fStop;
  75163. },
  75164. /**
  75165. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75166. */
  75167. set: function (value) {
  75168. this._circleOfConfusion.fStop = value;
  75169. },
  75170. enumerable: true,
  75171. configurable: true
  75172. });
  75173. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75174. get: function () {
  75175. return this._circleOfConfusion.focusDistance;
  75176. },
  75177. /**
  75178. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75179. */
  75180. set: function (value) {
  75181. this._circleOfConfusion.focusDistance = value;
  75182. },
  75183. enumerable: true,
  75184. configurable: true
  75185. });
  75186. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75187. get: function () {
  75188. return this._circleOfConfusion.lensSize;
  75189. },
  75190. /**
  75191. * 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.
  75192. */
  75193. set: function (value) {
  75194. this._circleOfConfusion.lensSize = value;
  75195. },
  75196. enumerable: true,
  75197. configurable: true
  75198. });
  75199. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75200. /**
  75201. * 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.
  75202. */
  75203. set: function (value) {
  75204. this._circleOfConfusion.depthTexture = value;
  75205. },
  75206. enumerable: true,
  75207. configurable: true
  75208. });
  75209. /**
  75210. * Disposes each of the internal effects for a given camera.
  75211. * @param camera The camera to dispose the effect on.
  75212. */
  75213. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75214. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75215. this._effects[effectIndex].dispose(camera);
  75216. }
  75217. };
  75218. /**
  75219. * Internal
  75220. */
  75221. DepthOfFieldEffect.prototype._updateEffects = function () {
  75222. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75223. this._effects[effectIndex].updateEffect();
  75224. }
  75225. };
  75226. /**
  75227. * Internal
  75228. * @returns if all the contained post processes are ready.
  75229. */
  75230. DepthOfFieldEffect.prototype._isReady = function () {
  75231. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75232. if (!this._effects[effectIndex].isReady()) {
  75233. return false;
  75234. }
  75235. }
  75236. return true;
  75237. };
  75238. return DepthOfFieldEffect;
  75239. }(BABYLON.PostProcessRenderEffect));
  75240. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75241. })(BABYLON || (BABYLON = {}));
  75242. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75243. var BABYLON;
  75244. (function (BABYLON) {
  75245. /**
  75246. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75247. */
  75248. var BloomMergePostProcess = /** @class */ (function (_super) {
  75249. __extends(BloomMergePostProcess, _super);
  75250. /**
  75251. * Creates a new instance of @see BloomMergePostProcess
  75252. * @param name The name of the effect.
  75253. * @param originalFromInput Post process which's input will be used for the merge.
  75254. * @param blurred Blurred highlights post process which's output will be used.
  75255. * @param weight Weight of the bloom to be added to the original input.
  75256. * @param options The required width/height ratio to downsize to before computing the render pass.
  75257. * @param camera The camera to apply the render pass to.
  75258. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75259. * @param engine The engine which the post process will be applied. (default: current engine)
  75260. * @param reusable If the post process can be reused on the same frame. (default: false)
  75261. * @param textureType Type of textures used when performing the post process. (default: 0)
  75262. * @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)
  75263. */
  75264. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75265. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75266. if (blockCompilation === void 0) { blockCompilation = false; }
  75267. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75268. _this.weight = weight;
  75269. _this.onApplyObservable.add(function (effect) {
  75270. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75271. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75272. effect.setFloat("bloomWeight", _this.weight);
  75273. });
  75274. if (!blockCompilation) {
  75275. _this.updateEffect();
  75276. }
  75277. return _this;
  75278. }
  75279. return BloomMergePostProcess;
  75280. }(BABYLON.PostProcess));
  75281. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75282. })(BABYLON || (BABYLON = {}));
  75283. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75284. var BABYLON;
  75285. (function (BABYLON) {
  75286. /**
  75287. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75288. */
  75289. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75290. __extends(ExtractHighlightsPostProcess, _super);
  75291. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75292. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75293. if (blockCompilation === void 0) { blockCompilation = false; }
  75294. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75295. /**
  75296. * The luminance threshold, pixels below this value will be set to black.
  75297. */
  75298. _this.threshold = 0.9;
  75299. /**
  75300. * Internal
  75301. */
  75302. _this._exposure = 1;
  75303. /**
  75304. * Post process which has the input texture to be used when performing highlight extraction
  75305. */
  75306. _this._inputPostProcess = null;
  75307. _this.onApplyObservable.add(function (effect) {
  75308. if (_this._inputPostProcess) {
  75309. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75310. }
  75311. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75312. effect.setFloat('exposure', _this._exposure);
  75313. });
  75314. return _this;
  75315. }
  75316. return ExtractHighlightsPostProcess;
  75317. }(BABYLON.PostProcess));
  75318. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75319. })(BABYLON || (BABYLON = {}));
  75320. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75321. var BABYLON;
  75322. (function (BABYLON) {
  75323. /**
  75324. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75325. */
  75326. var BloomEffect = /** @class */ (function (_super) {
  75327. __extends(BloomEffect, _super);
  75328. /**
  75329. * Creates a new instance of @see BloomEffect
  75330. * @param scene The scene the effect belongs to.
  75331. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75332. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75333. * @param bloomWeight The the strength of bloom.
  75334. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75335. * @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)
  75336. */
  75337. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75338. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75339. if (blockCompilation === void 0) { blockCompilation = false; }
  75340. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75341. return _this._effects;
  75342. }, true) || this;
  75343. _this.bloomScale = bloomScale;
  75344. /**
  75345. * Internal
  75346. */
  75347. _this._effects = [];
  75348. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75349. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75350. _this._blurX.alwaysForcePOT = true;
  75351. _this._blurX.autoClear = false;
  75352. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75353. _this._blurY.alwaysForcePOT = true;
  75354. _this._blurY.autoClear = false;
  75355. _this.kernel = bloomKernel;
  75356. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75357. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75358. _this._merge.autoClear = false;
  75359. _this._effects.push(_this._merge);
  75360. return _this;
  75361. }
  75362. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75363. /**
  75364. * The luminance threshold to find bright areas of the image to bloom.
  75365. */
  75366. get: function () {
  75367. return this._downscale.threshold;
  75368. },
  75369. set: function (value) {
  75370. this._downscale.threshold = value;
  75371. },
  75372. enumerable: true,
  75373. configurable: true
  75374. });
  75375. Object.defineProperty(BloomEffect.prototype, "weight", {
  75376. /**
  75377. * The strength of the bloom.
  75378. */
  75379. get: function () {
  75380. return this._merge.weight;
  75381. },
  75382. set: function (value) {
  75383. this._merge.weight = value;
  75384. },
  75385. enumerable: true,
  75386. configurable: true
  75387. });
  75388. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75389. /**
  75390. * Specifies the size of the bloom blur kernel, relative to the final output size
  75391. */
  75392. get: function () {
  75393. return this._blurX.kernel / this.bloomScale;
  75394. },
  75395. set: function (value) {
  75396. this._blurX.kernel = value * this.bloomScale;
  75397. this._blurY.kernel = value * this.bloomScale;
  75398. },
  75399. enumerable: true,
  75400. configurable: true
  75401. });
  75402. /**
  75403. * Disposes each of the internal effects for a given camera.
  75404. * @param camera The camera to dispose the effect on.
  75405. */
  75406. BloomEffect.prototype.disposeEffects = function (camera) {
  75407. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75408. this._effects[effectIndex].dispose(camera);
  75409. }
  75410. };
  75411. /**
  75412. * Internal
  75413. */
  75414. BloomEffect.prototype._updateEffects = function () {
  75415. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75416. this._effects[effectIndex].updateEffect();
  75417. }
  75418. };
  75419. /**
  75420. * Internal
  75421. * @returns if all the contained post processes are ready.
  75422. */
  75423. BloomEffect.prototype._isReady = function () {
  75424. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75425. if (!this._effects[effectIndex].isReady()) {
  75426. return false;
  75427. }
  75428. }
  75429. return true;
  75430. };
  75431. return BloomEffect;
  75432. }(BABYLON.PostProcessRenderEffect));
  75433. BABYLON.BloomEffect = BloomEffect;
  75434. })(BABYLON || (BABYLON = {}));
  75435. //# sourceMappingURL=babylon.bloomEffect.js.map
  75436. var BABYLON;
  75437. (function (BABYLON) {
  75438. /**
  75439. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75440. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75441. */
  75442. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75443. __extends(DefaultRenderingPipeline, _super);
  75444. /**
  75445. * @constructor
  75446. * @param {string} name - The rendering pipeline name
  75447. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75448. * @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)
  75449. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75450. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75451. */
  75452. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75453. if (automaticBuild === void 0) { automaticBuild = true; }
  75454. var _this = _super.call(this, scene.getEngine(), name) || this;
  75455. _this._originalCameras = [];
  75456. /**
  75457. * ID of the sharpen post process,
  75458. */
  75459. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75460. /**
  75461. * ID of the image processing post process;
  75462. */
  75463. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75464. /**
  75465. * ID of the Fast Approximate Anti-Aliasing post process;
  75466. */
  75467. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75468. /**
  75469. * ID of the chromatic aberration post process,
  75470. */
  75471. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75472. /**
  75473. * ID of the grain post process
  75474. */
  75475. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75476. /**
  75477. * Animations which can be used to tweak settings over a period of time
  75478. */
  75479. _this.animations = [];
  75480. _this._imageProcessingConfigurationObserver = null;
  75481. // Values
  75482. _this._sharpenEnabled = false;
  75483. _this._bloomEnabled = false;
  75484. _this._depthOfFieldEnabled = false;
  75485. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75486. _this._fxaaEnabled = false;
  75487. _this._imageProcessingEnabled = true;
  75488. _this._bloomScale = 0.5;
  75489. _this._chromaticAberrationEnabled = false;
  75490. _this._grainEnabled = false;
  75491. _this._buildAllowed = true;
  75492. _this._resizeObserver = null;
  75493. _this._hardwareScaleLevel = 1.0;
  75494. _this._bloomKernel = 64;
  75495. /**
  75496. * Specifies the weight of the bloom in the final rendering
  75497. */
  75498. _this._bloomWeight = 0.15;
  75499. /**
  75500. * Specifies the luma threshold for the area that will be blurred by the bloom
  75501. */
  75502. _this._bloomThreshold = 0.9;
  75503. _this._samples = 1;
  75504. _this._hasCleared = false;
  75505. _this._prevPostProcess = null;
  75506. _this._prevPrevPostProcess = null;
  75507. _this._cameras = cameras || [];
  75508. _this._originalCameras = _this._cameras.slice();
  75509. _this._buildAllowed = automaticBuild;
  75510. // Initialize
  75511. _this._scene = scene;
  75512. var caps = _this._scene.getEngine().getCaps();
  75513. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75514. // Misc
  75515. if (_this._hdr) {
  75516. if (caps.textureHalfFloatRender) {
  75517. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75518. }
  75519. else if (caps.textureFloatRender) {
  75520. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75521. }
  75522. }
  75523. else {
  75524. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75525. }
  75526. // Attach
  75527. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75528. var engine = _this._scene.getEngine();
  75529. // Create post processes before hand so they can be modified before enabled.
  75530. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75531. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75532. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75533. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75534. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75535. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75536. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75537. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75538. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75539. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75540. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75541. _this.bloomKernel = _this.bloomKernel;
  75542. });
  75543. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75544. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75545. });
  75546. _this._buildPipeline();
  75547. return _this;
  75548. }
  75549. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75550. get: function () {
  75551. return this._sharpenEnabled;
  75552. },
  75553. /**
  75554. * Enable or disable the sharpen process from the pipeline
  75555. */
  75556. set: function (enabled) {
  75557. if (this._sharpenEnabled === enabled) {
  75558. return;
  75559. }
  75560. this._sharpenEnabled = enabled;
  75561. this._buildPipeline();
  75562. },
  75563. enumerable: true,
  75564. configurable: true
  75565. });
  75566. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75567. /**
  75568. * Specifies the size of the bloom blur kernel, relative to the final output size
  75569. */
  75570. get: function () {
  75571. return this._bloomKernel;
  75572. },
  75573. set: function (value) {
  75574. this._bloomKernel = value;
  75575. this.bloom.kernel = value / this._hardwareScaleLevel;
  75576. },
  75577. enumerable: true,
  75578. configurable: true
  75579. });
  75580. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75581. get: function () {
  75582. return this._bloomWeight;
  75583. },
  75584. /**
  75585. * The strength of the bloom.
  75586. */
  75587. set: function (value) {
  75588. if (this._bloomWeight === value) {
  75589. return;
  75590. }
  75591. this.bloom.weight = value;
  75592. this._bloomWeight = value;
  75593. },
  75594. enumerable: true,
  75595. configurable: true
  75596. });
  75597. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75598. get: function () {
  75599. return this._bloomThreshold;
  75600. },
  75601. /**
  75602. * The strength of the bloom.
  75603. */
  75604. set: function (value) {
  75605. if (this._bloomThreshold === value) {
  75606. return;
  75607. }
  75608. this.bloom.threshold = value;
  75609. this._bloomThreshold = value;
  75610. },
  75611. enumerable: true,
  75612. configurable: true
  75613. });
  75614. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75615. get: function () {
  75616. return this._bloomScale;
  75617. },
  75618. /**
  75619. * The scale of the bloom, lower value will provide better performance.
  75620. */
  75621. set: function (value) {
  75622. if (this._bloomScale === value) {
  75623. return;
  75624. }
  75625. this._bloomScale = value;
  75626. // recreate bloom and dispose old as this setting is not dynamic
  75627. this._rebuildBloom();
  75628. this._buildPipeline();
  75629. },
  75630. enumerable: true,
  75631. configurable: true
  75632. });
  75633. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75634. get: function () {
  75635. return this._bloomEnabled;
  75636. },
  75637. /**
  75638. * Enable or disable the bloom from the pipeline
  75639. */
  75640. set: function (enabled) {
  75641. if (this._bloomEnabled === enabled) {
  75642. return;
  75643. }
  75644. this._bloomEnabled = enabled;
  75645. this._buildPipeline();
  75646. },
  75647. enumerable: true,
  75648. configurable: true
  75649. });
  75650. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75651. // recreate bloom and dispose old as this setting is not dynamic
  75652. var oldBloom = this.bloom;
  75653. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75654. this.bloom.threshold = oldBloom.threshold;
  75655. for (var i = 0; i < this._cameras.length; i++) {
  75656. oldBloom.disposeEffects(this._cameras[i]);
  75657. }
  75658. };
  75659. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75660. /**
  75661. * If the depth of field is enabled.
  75662. */
  75663. get: function () {
  75664. return this._depthOfFieldEnabled;
  75665. },
  75666. set: function (enabled) {
  75667. if (this._depthOfFieldEnabled === enabled) {
  75668. return;
  75669. }
  75670. this._depthOfFieldEnabled = enabled;
  75671. this._buildPipeline();
  75672. },
  75673. enumerable: true,
  75674. configurable: true
  75675. });
  75676. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75677. /**
  75678. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75679. */
  75680. get: function () {
  75681. return this._depthOfFieldBlurLevel;
  75682. },
  75683. set: function (value) {
  75684. if (this._depthOfFieldBlurLevel === value) {
  75685. return;
  75686. }
  75687. this._depthOfFieldBlurLevel = value;
  75688. // recreate dof and dispose old as this setting is not dynamic
  75689. var oldDof = this.depthOfField;
  75690. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75691. this.depthOfField.focalLength = oldDof.focalLength;
  75692. this.depthOfField.focusDistance = oldDof.focusDistance;
  75693. this.depthOfField.fStop = oldDof.fStop;
  75694. this.depthOfField.lensSize = oldDof.lensSize;
  75695. for (var i = 0; i < this._cameras.length; i++) {
  75696. oldDof.disposeEffects(this._cameras[i]);
  75697. }
  75698. this._buildPipeline();
  75699. },
  75700. enumerable: true,
  75701. configurable: true
  75702. });
  75703. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75704. get: function () {
  75705. return this._fxaaEnabled;
  75706. },
  75707. /**
  75708. * If the anti aliasing is enabled.
  75709. */
  75710. set: function (enabled) {
  75711. if (this._fxaaEnabled === enabled) {
  75712. return;
  75713. }
  75714. this._fxaaEnabled = enabled;
  75715. this._buildPipeline();
  75716. },
  75717. enumerable: true,
  75718. configurable: true
  75719. });
  75720. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75721. get: function () {
  75722. return this._samples;
  75723. },
  75724. /**
  75725. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75726. */
  75727. set: function (sampleCount) {
  75728. if (this._samples === sampleCount) {
  75729. return;
  75730. }
  75731. this._samples = sampleCount;
  75732. this._buildPipeline();
  75733. },
  75734. enumerable: true,
  75735. configurable: true
  75736. });
  75737. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75738. get: function () {
  75739. return this._imageProcessingEnabled;
  75740. },
  75741. /**
  75742. * If image processing is enabled.
  75743. */
  75744. set: function (enabled) {
  75745. if (this._imageProcessingEnabled === enabled) {
  75746. return;
  75747. }
  75748. this._imageProcessingEnabled = enabled;
  75749. this._buildPipeline();
  75750. },
  75751. enumerable: true,
  75752. configurable: true
  75753. });
  75754. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75755. get: function () {
  75756. return this._chromaticAberrationEnabled;
  75757. },
  75758. /**
  75759. * Enable or disable the chromaticAberration process from the pipeline
  75760. */
  75761. set: function (enabled) {
  75762. if (this._chromaticAberrationEnabled === enabled) {
  75763. return;
  75764. }
  75765. this._chromaticAberrationEnabled = enabled;
  75766. this._buildPipeline();
  75767. },
  75768. enumerable: true,
  75769. configurable: true
  75770. });
  75771. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75772. get: function () {
  75773. return this._grainEnabled;
  75774. },
  75775. /**
  75776. * Enable or disable the grain process from the pipeline
  75777. */
  75778. set: function (enabled) {
  75779. if (this._grainEnabled === enabled) {
  75780. return;
  75781. }
  75782. this._grainEnabled = enabled;
  75783. this._buildPipeline();
  75784. },
  75785. enumerable: true,
  75786. configurable: true
  75787. });
  75788. /**
  75789. * Force the compilation of the entire pipeline.
  75790. */
  75791. DefaultRenderingPipeline.prototype.prepare = function () {
  75792. var previousState = this._buildAllowed;
  75793. this._buildAllowed = true;
  75794. this._buildPipeline();
  75795. this._buildAllowed = previousState;
  75796. };
  75797. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75798. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75799. if (this._hasCleared) {
  75800. postProcess.autoClear = false;
  75801. }
  75802. else {
  75803. postProcess.autoClear = true;
  75804. this._scene.autoClear = false;
  75805. this._hasCleared = true;
  75806. }
  75807. if (!skipTextureSharing) {
  75808. if (this._prevPrevPostProcess) {
  75809. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75810. }
  75811. else {
  75812. postProcess.useOwnOutput();
  75813. }
  75814. if (this._prevPostProcess) {
  75815. this._prevPrevPostProcess = this._prevPostProcess;
  75816. }
  75817. this._prevPostProcess = postProcess;
  75818. }
  75819. };
  75820. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75821. var _this = this;
  75822. if (!this._buildAllowed) {
  75823. return;
  75824. }
  75825. this._scene.autoClear = true;
  75826. var engine = this._scene.getEngine();
  75827. this._disposePostProcesses();
  75828. if (this._cameras !== null) {
  75829. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75830. // get back cameras to be used to reattach pipeline
  75831. this._cameras = this._originalCameras.slice();
  75832. }
  75833. this._reset();
  75834. this._prevPostProcess = null;
  75835. this._prevPrevPostProcess = null;
  75836. this._hasCleared = false;
  75837. if (this.depthOfFieldEnabled) {
  75838. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75839. this.depthOfField.depthTexture = depthTexture;
  75840. if (!this.depthOfField._isReady()) {
  75841. this.depthOfField._updateEffects();
  75842. }
  75843. this.addEffect(this.depthOfField);
  75844. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75845. }
  75846. if (this.bloomEnabled) {
  75847. if (!this.bloom._isReady()) {
  75848. this.bloom._updateEffects();
  75849. }
  75850. this.addEffect(this.bloom);
  75851. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75852. }
  75853. if (this._imageProcessingEnabled) {
  75854. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75855. if (this._hdr) {
  75856. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75857. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75858. }
  75859. else {
  75860. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75861. }
  75862. }
  75863. if (this.sharpenEnabled) {
  75864. if (!this.sharpen.isReady()) {
  75865. this.sharpen.updateEffect();
  75866. }
  75867. this.addEffect(this._sharpenEffect);
  75868. this._setAutoClearAndTextureSharing(this.sharpen);
  75869. }
  75870. if (this.grainEnabled) {
  75871. if (!this.grain.isReady()) {
  75872. this.grain.updateEffect();
  75873. }
  75874. this.addEffect(this._grainEffect);
  75875. this._setAutoClearAndTextureSharing(this.grain);
  75876. }
  75877. if (this.chromaticAberrationEnabled) {
  75878. if (!this.chromaticAberration.isReady()) {
  75879. this.chromaticAberration.updateEffect();
  75880. }
  75881. this.addEffect(this._chromaticAberrationEffect);
  75882. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75883. }
  75884. if (this.fxaaEnabled) {
  75885. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75886. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75887. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75888. }
  75889. if (this._cameras !== null) {
  75890. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75891. }
  75892. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75893. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75894. }
  75895. };
  75896. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75897. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75898. for (var i = 0; i < this._cameras.length; i++) {
  75899. var camera = this._cameras[i];
  75900. if (this.imageProcessing) {
  75901. this.imageProcessing.dispose(camera);
  75902. }
  75903. if (this.fxaa) {
  75904. this.fxaa.dispose(camera);
  75905. }
  75906. // These are created in the constructor and should not be disposed on every pipeline change
  75907. if (disposeNonRecreated) {
  75908. if (this.sharpen) {
  75909. this.sharpen.dispose(camera);
  75910. }
  75911. if (this.depthOfField) {
  75912. this.depthOfField.disposeEffects(camera);
  75913. }
  75914. if (this.bloom) {
  75915. this.bloom.disposeEffects(camera);
  75916. }
  75917. if (this.chromaticAberration) {
  75918. this.chromaticAberration.dispose(camera);
  75919. }
  75920. if (this.grain) {
  75921. this.grain.dispose(camera);
  75922. }
  75923. }
  75924. }
  75925. this.imageProcessing = null;
  75926. this.fxaa = null;
  75927. if (disposeNonRecreated) {
  75928. this.sharpen = null;
  75929. this._sharpenEffect = null;
  75930. this.depthOfField = null;
  75931. this.bloom = null;
  75932. this.chromaticAberration = null;
  75933. this._chromaticAberrationEffect = null;
  75934. this.grain = null;
  75935. this._grainEffect = null;
  75936. }
  75937. };
  75938. /**
  75939. * Dispose of the pipeline and stop all post processes
  75940. */
  75941. DefaultRenderingPipeline.prototype.dispose = function () {
  75942. this._disposePostProcesses(true);
  75943. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75944. this._scene.autoClear = true;
  75945. if (this._resizeObserver) {
  75946. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75947. this._resizeObserver = null;
  75948. }
  75949. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75950. _super.prototype.dispose.call(this);
  75951. };
  75952. /**
  75953. * Serialize the rendering pipeline (Used when exporting)
  75954. * @returns the serialized object
  75955. */
  75956. DefaultRenderingPipeline.prototype.serialize = function () {
  75957. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75958. serializationObject.customType = "DefaultRenderingPipeline";
  75959. return serializationObject;
  75960. };
  75961. /**
  75962. * Parse the serialized pipeline
  75963. * @param source Source pipeline.
  75964. * @param scene The scene to load the pipeline to.
  75965. * @param rootUrl The URL of the serialized pipeline.
  75966. * @returns An instantiated pipeline from the serialized object.
  75967. */
  75968. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75969. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75970. };
  75971. __decorate([
  75972. BABYLON.serialize()
  75973. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75974. __decorate([
  75975. BABYLON.serialize()
  75976. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75977. __decorate([
  75978. BABYLON.serialize()
  75979. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75980. __decorate([
  75981. BABYLON.serialize()
  75982. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75983. __decorate([
  75984. BABYLON.serialize()
  75985. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75986. __decorate([
  75987. BABYLON.serialize()
  75988. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75989. __decorate([
  75990. BABYLON.serialize()
  75991. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75992. __decorate([
  75993. BABYLON.serialize()
  75994. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75995. __decorate([
  75996. BABYLON.serialize()
  75997. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75998. __decorate([
  75999. BABYLON.serialize()
  76000. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76001. __decorate([
  76002. BABYLON.serialize()
  76003. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76004. __decorate([
  76005. BABYLON.serialize()
  76006. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76007. __decorate([
  76008. BABYLON.serialize()
  76009. ], DefaultRenderingPipeline.prototype, "samples", null);
  76010. __decorate([
  76011. BABYLON.serialize()
  76012. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76013. __decorate([
  76014. BABYLON.serialize()
  76015. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76016. __decorate([
  76017. BABYLON.serialize()
  76018. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76019. return DefaultRenderingPipeline;
  76020. }(BABYLON.PostProcessRenderPipeline));
  76021. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76022. })(BABYLON || (BABYLON = {}));
  76023. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76024. var BABYLON;
  76025. (function (BABYLON) {
  76026. /**
  76027. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76028. */
  76029. var GeometryBufferRenderer = /** @class */ (function () {
  76030. /**
  76031. * Creates a new G Buffer for the scene
  76032. * @param scene The scene the buffer belongs to
  76033. * @param ratio How big is the buffer related to the main canvas.
  76034. */
  76035. function GeometryBufferRenderer(scene, ratio) {
  76036. if (ratio === void 0) { ratio = 1; }
  76037. this._enablePosition = false;
  76038. this._scene = scene;
  76039. this._ratio = ratio;
  76040. // Render target
  76041. this._createRenderTargets();
  76042. }
  76043. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76044. /**
  76045. * Set the render list (meshes to be rendered) used in the G buffer.
  76046. */
  76047. set: function (meshes) {
  76048. this._multiRenderTarget.renderList = meshes;
  76049. },
  76050. enumerable: true,
  76051. configurable: true
  76052. });
  76053. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76054. /**
  76055. * Gets wether or not G buffer are supported by the running hardware.
  76056. * This requires draw buffer supports
  76057. */
  76058. get: function () {
  76059. return this._multiRenderTarget.isSupported;
  76060. },
  76061. enumerable: true,
  76062. configurable: true
  76063. });
  76064. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76065. /**
  76066. * Gets wether or not position are enabled for the G buffer.
  76067. */
  76068. get: function () {
  76069. return this._enablePosition;
  76070. },
  76071. /**
  76072. * Sets wether or not position are enabled for the G buffer.
  76073. */
  76074. set: function (enable) {
  76075. this._enablePosition = enable;
  76076. this.dispose();
  76077. this._createRenderTargets();
  76078. },
  76079. enumerable: true,
  76080. configurable: true
  76081. });
  76082. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76083. /**
  76084. * Gets the scene associated with the buffer.
  76085. */
  76086. get: function () {
  76087. return this._scene;
  76088. },
  76089. enumerable: true,
  76090. configurable: true
  76091. });
  76092. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76093. /**
  76094. * Gets the ratio used by the buffer during its creation.
  76095. * How big is the buffer related to the main canvas.
  76096. */
  76097. get: function () {
  76098. return this._ratio;
  76099. },
  76100. enumerable: true,
  76101. configurable: true
  76102. });
  76103. /**
  76104. * Checks wether everything is ready to render a submesh to the G buffer.
  76105. * @param subMesh the submesh to check readiness for
  76106. * @param useInstances is the mesh drawn using instance or not
  76107. * @returns true if ready otherwise false
  76108. */
  76109. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76110. var material = subMesh.getMaterial();
  76111. if (material && material.disableDepthWrite) {
  76112. return false;
  76113. }
  76114. var defines = [];
  76115. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76116. var mesh = subMesh.getMesh();
  76117. // Alpha test
  76118. if (material && material.needAlphaTesting()) {
  76119. defines.push("#define ALPHATEST");
  76120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76121. attribs.push(BABYLON.VertexBuffer.UVKind);
  76122. defines.push("#define UV1");
  76123. }
  76124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76125. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76126. defines.push("#define UV2");
  76127. }
  76128. }
  76129. // Buffers
  76130. if (this._enablePosition) {
  76131. defines.push("#define POSITION");
  76132. }
  76133. // Bones
  76134. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76135. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76136. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76137. if (mesh.numBoneInfluencers > 4) {
  76138. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76139. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76140. }
  76141. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76142. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76143. }
  76144. else {
  76145. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76146. }
  76147. // Instances
  76148. if (useInstances) {
  76149. defines.push("#define INSTANCES");
  76150. attribs.push("world0");
  76151. attribs.push("world1");
  76152. attribs.push("world2");
  76153. attribs.push("world3");
  76154. }
  76155. // Get correct effect
  76156. var join = defines.join("\n");
  76157. if (this._cachedDefines !== join) {
  76158. this._cachedDefines = join;
  76159. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76160. }
  76161. return this._effect.isReady();
  76162. };
  76163. /**
  76164. * Gets the current underlying G Buffer.
  76165. * @returns the buffer
  76166. */
  76167. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76168. return this._multiRenderTarget;
  76169. };
  76170. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76171. /**
  76172. * Gets the number of samples used to render the buffer (anti aliasing).
  76173. */
  76174. get: function () {
  76175. return this._multiRenderTarget.samples;
  76176. },
  76177. /**
  76178. * Sets the number of samples used to render the buffer (anti aliasing).
  76179. */
  76180. set: function (value) {
  76181. this._multiRenderTarget.samples = value;
  76182. },
  76183. enumerable: true,
  76184. configurable: true
  76185. });
  76186. /**
  76187. * Disposes the renderer and frees up associated resources.
  76188. */
  76189. GeometryBufferRenderer.prototype.dispose = function () {
  76190. this.getGBuffer().dispose();
  76191. };
  76192. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76193. var _this = this;
  76194. var engine = this._scene.getEngine();
  76195. var count = this._enablePosition ? 3 : 2;
  76196. 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 });
  76197. if (!this.isSupported) {
  76198. return;
  76199. }
  76200. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76201. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76202. this._multiRenderTarget.refreshRate = 1;
  76203. this._multiRenderTarget.renderParticles = false;
  76204. this._multiRenderTarget.renderList = null;
  76205. // set default depth value to 1.0 (far away)
  76206. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76207. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76208. });
  76209. // Custom render function
  76210. var renderSubMesh = function (subMesh) {
  76211. var mesh = subMesh.getRenderingMesh();
  76212. var scene = _this._scene;
  76213. var engine = scene.getEngine();
  76214. var material = subMesh.getMaterial();
  76215. if (!material) {
  76216. return;
  76217. }
  76218. // Culling
  76219. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76220. // Managing instances
  76221. var batch = mesh._getInstancesRenderList(subMesh._id);
  76222. if (batch.mustReturn) {
  76223. return;
  76224. }
  76225. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76226. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76227. engine.enableEffect(_this._effect);
  76228. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76229. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76230. _this._effect.setMatrix("view", scene.getViewMatrix());
  76231. // Alpha test
  76232. if (material && material.needAlphaTesting()) {
  76233. var alphaTexture = material.getAlphaTestTexture();
  76234. if (alphaTexture) {
  76235. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76236. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76237. }
  76238. }
  76239. // Bones
  76240. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76241. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76242. }
  76243. // Draw
  76244. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76245. }
  76246. };
  76247. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76248. var index;
  76249. if (depthOnlySubMeshes.length) {
  76250. engine.setColorWrite(false);
  76251. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76252. renderSubMesh(depthOnlySubMeshes.data[index]);
  76253. }
  76254. engine.setColorWrite(true);
  76255. }
  76256. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76257. renderSubMesh(opaqueSubMeshes.data[index]);
  76258. }
  76259. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76260. renderSubMesh(alphaTestSubMeshes.data[index]);
  76261. }
  76262. };
  76263. };
  76264. return GeometryBufferRenderer;
  76265. }());
  76266. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76267. })(BABYLON || (BABYLON = {}));
  76268. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76269. var BABYLON;
  76270. (function (BABYLON) {
  76271. var RefractionPostProcess = /** @class */ (function (_super) {
  76272. __extends(RefractionPostProcess, _super);
  76273. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76274. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76275. _this.color = color;
  76276. _this.depth = depth;
  76277. _this.colorLevel = colorLevel;
  76278. _this._ownRefractionTexture = true;
  76279. _this.onActivateObservable.add(function (cam) {
  76280. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76281. });
  76282. _this.onApplyObservable.add(function (effect) {
  76283. effect.setColor3("baseColor", _this.color);
  76284. effect.setFloat("depth", _this.depth);
  76285. effect.setFloat("colorLevel", _this.colorLevel);
  76286. effect.setTexture("refractionSampler", _this._refTexture);
  76287. });
  76288. return _this;
  76289. }
  76290. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76291. /**
  76292. * Gets or sets the refraction texture
  76293. * Please note that you are responsible for disposing the texture if you set it manually
  76294. */
  76295. get: function () {
  76296. return this._refTexture;
  76297. },
  76298. set: function (value) {
  76299. if (this._refTexture && this._ownRefractionTexture) {
  76300. this._refTexture.dispose();
  76301. }
  76302. this._refTexture = value;
  76303. this._ownRefractionTexture = false;
  76304. },
  76305. enumerable: true,
  76306. configurable: true
  76307. });
  76308. // Methods
  76309. RefractionPostProcess.prototype.dispose = function (camera) {
  76310. if (this._refTexture && this._ownRefractionTexture) {
  76311. this._refTexture.dispose();
  76312. this._refTexture = null;
  76313. }
  76314. _super.prototype.dispose.call(this, camera);
  76315. };
  76316. return RefractionPostProcess;
  76317. }(BABYLON.PostProcess));
  76318. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76319. })(BABYLON || (BABYLON = {}));
  76320. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76321. var BABYLON;
  76322. (function (BABYLON) {
  76323. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76324. __extends(BlackAndWhitePostProcess, _super);
  76325. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76326. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76327. _this.degree = 1;
  76328. _this.onApplyObservable.add(function (effect) {
  76329. effect.setFloat("degree", _this.degree);
  76330. });
  76331. return _this;
  76332. }
  76333. return BlackAndWhitePostProcess;
  76334. }(BABYLON.PostProcess));
  76335. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76336. })(BABYLON || (BABYLON = {}));
  76337. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76338. var BABYLON;
  76339. (function (BABYLON) {
  76340. /**
  76341. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76342. * input texture to perform effects such as edge detection or sharpening
  76343. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76344. */
  76345. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76346. __extends(ConvolutionPostProcess, _super);
  76347. /**
  76348. * Creates a new instance ConvolutionPostProcess
  76349. * @param name The name of the effect.
  76350. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76351. * @param options The required width/height ratio to downsize to before computing the render pass.
  76352. * @param camera The camera to apply the render pass to.
  76353. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76354. * @param engine The engine which the post process will be applied. (default: current engine)
  76355. * @param reusable If the post process can be reused on the same frame. (default: false)
  76356. * @param textureType Type of textures used when performing the post process. (default: 0)
  76357. */
  76358. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76359. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76360. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76361. _this.kernel = kernel;
  76362. _this.onApply = function (effect) {
  76363. effect.setFloat2("screenSize", _this.width, _this.height);
  76364. effect.setArray("kernel", _this.kernel);
  76365. };
  76366. return _this;
  76367. }
  76368. // Statics
  76369. /**
  76370. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76371. */
  76372. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76373. /**
  76374. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76375. */
  76376. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76377. /**
  76378. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76379. */
  76380. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76381. /**
  76382. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76383. */
  76384. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76385. /**
  76386. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76387. */
  76388. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76389. /**
  76390. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76391. */
  76392. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76393. return ConvolutionPostProcess;
  76394. }(BABYLON.PostProcess));
  76395. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76396. })(BABYLON || (BABYLON = {}));
  76397. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76398. var BABYLON;
  76399. (function (BABYLON) {
  76400. var FilterPostProcess = /** @class */ (function (_super) {
  76401. __extends(FilterPostProcess, _super);
  76402. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76403. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76404. _this.kernelMatrix = kernelMatrix;
  76405. _this.onApply = function (effect) {
  76406. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76407. };
  76408. return _this;
  76409. }
  76410. return FilterPostProcess;
  76411. }(BABYLON.PostProcess));
  76412. BABYLON.FilterPostProcess = FilterPostProcess;
  76413. })(BABYLON || (BABYLON = {}));
  76414. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76415. var BABYLON;
  76416. (function (BABYLON) {
  76417. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76418. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76419. __extends(VolumetricLightScatteringPostProcess, _super);
  76420. /**
  76421. * @constructor
  76422. * @param {string} name - The post-process name
  76423. * @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)
  76424. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76425. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76426. * @param {number} samples - The post-process quality, default 100
  76427. * @param {number} samplingMode - The post-process filtering mode
  76428. * @param {BABYLON.Engine} engine - The babylon engine
  76429. * @param {boolean} reusable - If the post-process is reusable
  76430. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76431. */
  76432. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76433. if (samples === void 0) { samples = 100; }
  76434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76435. 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;
  76436. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76437. /**
  76438. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76439. */
  76440. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76441. /**
  76442. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76443. */
  76444. _this.useCustomMeshPosition = false;
  76445. /**
  76446. * If the post-process should inverse the light scattering direction
  76447. */
  76448. _this.invert = true;
  76449. /**
  76450. * Array containing the excluded meshes not rendered in the internal pass
  76451. */
  76452. _this.excludedMeshes = new Array();
  76453. /**
  76454. * Controls the overall intensity of the post-process
  76455. */
  76456. _this.exposure = 0.3;
  76457. /**
  76458. * Dissipates each sample's contribution in range [0, 1]
  76459. */
  76460. _this.decay = 0.96815;
  76461. /**
  76462. * Controls the overall intensity of each sample
  76463. */
  76464. _this.weight = 0.58767;
  76465. /**
  76466. * Controls the density of each sample
  76467. */
  76468. _this.density = 0.926;
  76469. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76470. engine = scene.getEngine();
  76471. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76472. // Configure mesh
  76473. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76474. // Configure
  76475. _this._createPass(scene, ratio.passRatio || ratio);
  76476. _this.onActivate = function (camera) {
  76477. if (!_this.isSupported) {
  76478. _this.dispose(camera);
  76479. }
  76480. _this.onActivate = null;
  76481. };
  76482. _this.onApplyObservable.add(function (effect) {
  76483. _this._updateMeshScreenCoordinates(scene);
  76484. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76485. effect.setFloat("exposure", _this.exposure);
  76486. effect.setFloat("decay", _this.decay);
  76487. effect.setFloat("weight", _this.weight);
  76488. effect.setFloat("density", _this.density);
  76489. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76490. });
  76491. return _this;
  76492. }
  76493. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76494. get: function () {
  76495. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76496. return false;
  76497. },
  76498. set: function (useDiffuseColor) {
  76499. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76500. },
  76501. enumerable: true,
  76502. configurable: true
  76503. });
  76504. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76505. return "VolumetricLightScatteringPostProcess";
  76506. };
  76507. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76508. var mesh = subMesh.getMesh();
  76509. // Render this.mesh as default
  76510. if (mesh === this.mesh && mesh.material) {
  76511. return mesh.material.isReady(mesh);
  76512. }
  76513. var defines = [];
  76514. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76515. var material = subMesh.getMaterial();
  76516. // Alpha test
  76517. if (material) {
  76518. if (material.needAlphaTesting()) {
  76519. defines.push("#define ALPHATEST");
  76520. }
  76521. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76522. attribs.push(BABYLON.VertexBuffer.UVKind);
  76523. defines.push("#define UV1");
  76524. }
  76525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76526. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76527. defines.push("#define UV2");
  76528. }
  76529. }
  76530. // Bones
  76531. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76532. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76533. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76534. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76535. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76536. }
  76537. else {
  76538. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76539. }
  76540. // Instances
  76541. if (useInstances) {
  76542. defines.push("#define INSTANCES");
  76543. attribs.push("world0");
  76544. attribs.push("world1");
  76545. attribs.push("world2");
  76546. attribs.push("world3");
  76547. }
  76548. // Get correct effect
  76549. var join = defines.join("\n");
  76550. if (this._cachedDefines !== join) {
  76551. this._cachedDefines = join;
  76552. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76553. }
  76554. return this._volumetricLightScatteringPass.isReady();
  76555. };
  76556. /**
  76557. * Sets the new light position for light scattering effect
  76558. * @param {BABYLON.Vector3} The new custom light position
  76559. */
  76560. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76561. this.customMeshPosition = position;
  76562. };
  76563. /**
  76564. * Returns the light position for light scattering effect
  76565. * @return {BABYLON.Vector3} The custom light position
  76566. */
  76567. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76568. return this.customMeshPosition;
  76569. };
  76570. /**
  76571. * Disposes the internal assets and detaches the post-process from the camera
  76572. */
  76573. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76574. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76575. if (rttIndex !== -1) {
  76576. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76577. }
  76578. this._volumetricLightScatteringRTT.dispose();
  76579. _super.prototype.dispose.call(this, camera);
  76580. };
  76581. /**
  76582. * Returns the render target texture used by the post-process
  76583. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76584. */
  76585. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76586. return this._volumetricLightScatteringRTT;
  76587. };
  76588. // Private methods
  76589. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76590. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76591. return true;
  76592. }
  76593. return false;
  76594. };
  76595. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76596. var _this = this;
  76597. var engine = scene.getEngine();
  76598. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76599. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76600. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76601. this._volumetricLightScatteringRTT.renderList = null;
  76602. this._volumetricLightScatteringRTT.renderParticles = false;
  76603. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76604. var camera = this.getCamera();
  76605. if (camera) {
  76606. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76607. }
  76608. else {
  76609. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76610. }
  76611. // Custom render function for submeshes
  76612. var renderSubMesh = function (subMesh) {
  76613. var mesh = subMesh.getRenderingMesh();
  76614. if (_this._meshExcluded(mesh)) {
  76615. return;
  76616. }
  76617. var material = subMesh.getMaterial();
  76618. if (!material) {
  76619. return;
  76620. }
  76621. var scene = mesh.getScene();
  76622. var engine = scene.getEngine();
  76623. // Culling
  76624. engine.setState(material.backFaceCulling);
  76625. // Managing instances
  76626. var batch = mesh._getInstancesRenderList(subMesh._id);
  76627. if (batch.mustReturn) {
  76628. return;
  76629. }
  76630. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76631. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76632. var effect = _this._volumetricLightScatteringPass;
  76633. if (mesh === _this.mesh) {
  76634. if (subMesh.effect) {
  76635. effect = subMesh.effect;
  76636. }
  76637. else {
  76638. effect = material.getEffect();
  76639. }
  76640. }
  76641. engine.enableEffect(effect);
  76642. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76643. if (mesh === _this.mesh) {
  76644. material.bind(mesh.getWorldMatrix(), mesh);
  76645. }
  76646. else {
  76647. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76648. // Alpha test
  76649. if (material && material.needAlphaTesting()) {
  76650. var alphaTexture = material.getAlphaTestTexture();
  76651. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76652. if (alphaTexture) {
  76653. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76654. }
  76655. }
  76656. // Bones
  76657. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76658. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76659. }
  76660. }
  76661. // Draw
  76662. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76663. }
  76664. };
  76665. // Render target texture callbacks
  76666. var savedSceneClearColor;
  76667. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76668. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76669. savedSceneClearColor = scene.clearColor;
  76670. scene.clearColor = sceneClearColor;
  76671. });
  76672. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76673. scene.clearColor = savedSceneClearColor;
  76674. });
  76675. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76676. var engine = scene.getEngine();
  76677. var index;
  76678. if (depthOnlySubMeshes.length) {
  76679. engine.setColorWrite(false);
  76680. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76681. renderSubMesh(depthOnlySubMeshes.data[index]);
  76682. }
  76683. engine.setColorWrite(true);
  76684. }
  76685. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76686. renderSubMesh(opaqueSubMeshes.data[index]);
  76687. }
  76688. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76689. renderSubMesh(alphaTestSubMeshes.data[index]);
  76690. }
  76691. if (transparentSubMeshes.length) {
  76692. // Sort sub meshes
  76693. for (index = 0; index < transparentSubMeshes.length; index++) {
  76694. var submesh = transparentSubMeshes.data[index];
  76695. var boundingInfo = submesh.getBoundingInfo();
  76696. if (boundingInfo && scene.activeCamera) {
  76697. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76698. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76699. }
  76700. }
  76701. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76702. sortedArray.sort(function (a, b) {
  76703. // Alpha index first
  76704. if (a._alphaIndex > b._alphaIndex) {
  76705. return 1;
  76706. }
  76707. if (a._alphaIndex < b._alphaIndex) {
  76708. return -1;
  76709. }
  76710. // Then distance to camera
  76711. if (a._distanceToCamera < b._distanceToCamera) {
  76712. return 1;
  76713. }
  76714. if (a._distanceToCamera > b._distanceToCamera) {
  76715. return -1;
  76716. }
  76717. return 0;
  76718. });
  76719. // Render sub meshes
  76720. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76721. for (index = 0; index < sortedArray.length; index++) {
  76722. renderSubMesh(sortedArray[index]);
  76723. }
  76724. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76725. }
  76726. };
  76727. };
  76728. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76729. var transform = scene.getTransformMatrix();
  76730. var meshPosition;
  76731. if (this.useCustomMeshPosition) {
  76732. meshPosition = this.customMeshPosition;
  76733. }
  76734. else if (this.attachedNode) {
  76735. meshPosition = this.attachedNode.position;
  76736. }
  76737. else {
  76738. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76739. }
  76740. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76741. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76742. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76743. if (this.invert)
  76744. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76745. };
  76746. // Static methods
  76747. /**
  76748. * Creates a default mesh for the Volumeric Light Scattering post-process
  76749. * @param {string} The mesh name
  76750. * @param {BABYLON.Scene} The scene where to create the mesh
  76751. * @return {BABYLON.Mesh} the default mesh
  76752. */
  76753. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76754. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76755. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76756. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76757. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76758. mesh.material = material;
  76759. return mesh;
  76760. };
  76761. __decorate([
  76762. BABYLON.serializeAsVector3()
  76763. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76764. __decorate([
  76765. BABYLON.serialize()
  76766. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76767. __decorate([
  76768. BABYLON.serialize()
  76769. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76770. __decorate([
  76771. BABYLON.serializeAsMeshReference()
  76772. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76773. __decorate([
  76774. BABYLON.serialize()
  76775. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76776. __decorate([
  76777. BABYLON.serialize()
  76778. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76779. __decorate([
  76780. BABYLON.serialize()
  76781. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76782. __decorate([
  76783. BABYLON.serialize()
  76784. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76785. __decorate([
  76786. BABYLON.serialize()
  76787. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76788. return VolumetricLightScatteringPostProcess;
  76789. }(BABYLON.PostProcess));
  76790. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76791. })(BABYLON || (BABYLON = {}));
  76792. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76793. //
  76794. // This post-process allows the modification of rendered colors by using
  76795. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76796. //
  76797. // The object needs to be provided an url to a texture containing the color
  76798. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76799. // Use an image editing software to tweak the LUT to match your needs.
  76800. //
  76801. // For an example of a color LUT, see here:
  76802. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76803. // For explanations on color grading, see here:
  76804. // http://udn.epicgames.com/Three/ColorGrading.html
  76805. //
  76806. var BABYLON;
  76807. (function (BABYLON) {
  76808. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76809. __extends(ColorCorrectionPostProcess, _super);
  76810. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76811. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76812. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76813. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76814. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76815. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76816. _this.onApply = function (effect) {
  76817. effect.setTexture("colorTable", _this._colorTableTexture);
  76818. };
  76819. return _this;
  76820. }
  76821. return ColorCorrectionPostProcess;
  76822. }(BABYLON.PostProcess));
  76823. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76824. })(BABYLON || (BABYLON = {}));
  76825. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76826. var BABYLON;
  76827. (function (BABYLON) {
  76828. /** Defines operator used for tonemapping */
  76829. var TonemappingOperator;
  76830. (function (TonemappingOperator) {
  76831. /** Hable */
  76832. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76833. /** Reinhard */
  76834. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76835. /** HejiDawson */
  76836. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76837. /** Photographic */
  76838. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76839. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76840. ;
  76841. /**
  76842. * Defines a post process to apply tone mapping
  76843. */
  76844. var TonemapPostProcess = /** @class */ (function (_super) {
  76845. __extends(TonemapPostProcess, _super);
  76846. /**
  76847. * Creates a new TonemapPostProcess
  76848. * @param name defines the name of the postprocess
  76849. * @param _operator defines the operator to use
  76850. * @param exposureAdjustment defines the required exposure adjustement
  76851. * @param camera defines the camera to use (can be null)
  76852. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76853. * @param engine defines the hosting engine (can be ignore if camera is set)
  76854. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76855. */
  76856. function TonemapPostProcess(name, _operator,
  76857. /** Defines the required exposure adjustement */
  76858. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76860. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76861. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76862. _this._operator = _operator;
  76863. _this.exposureAdjustment = exposureAdjustment;
  76864. var defines = "#define ";
  76865. if (_this._operator === TonemappingOperator.Hable)
  76866. defines += "HABLE_TONEMAPPING";
  76867. else if (_this._operator === TonemappingOperator.Reinhard)
  76868. defines += "REINHARD_TONEMAPPING";
  76869. else if (_this._operator === TonemappingOperator.HejiDawson)
  76870. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76871. else if (_this._operator === TonemappingOperator.Photographic)
  76872. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76873. //sadly a second call to create the effect.
  76874. _this.updateEffect(defines);
  76875. _this.onApply = function (effect) {
  76876. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76877. };
  76878. return _this;
  76879. }
  76880. return TonemapPostProcess;
  76881. }(BABYLON.PostProcess));
  76882. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76883. })(BABYLON || (BABYLON = {}));
  76884. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76885. var BABYLON;
  76886. (function (BABYLON) {
  76887. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76888. __extends(DisplayPassPostProcess, _super);
  76889. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76890. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76891. }
  76892. return DisplayPassPostProcess;
  76893. }(BABYLON.PostProcess));
  76894. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76895. })(BABYLON || (BABYLON = {}));
  76896. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76897. var BABYLON;
  76898. (function (BABYLON) {
  76899. var HighlightsPostProcess = /** @class */ (function (_super) {
  76900. __extends(HighlightsPostProcess, _super);
  76901. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76902. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76903. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76904. }
  76905. return HighlightsPostProcess;
  76906. }(BABYLON.PostProcess));
  76907. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76908. })(BABYLON || (BABYLON = {}));
  76909. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76910. var BABYLON;
  76911. (function (BABYLON) {
  76912. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76913. __extends(ImageProcessingPostProcess, _super);
  76914. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76915. if (camera === void 0) { camera = null; }
  76916. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76917. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76918. _this._fromLinearSpace = true;
  76919. /**
  76920. * Defines cache preventing GC.
  76921. */
  76922. _this._defines = {
  76923. IMAGEPROCESSING: false,
  76924. VIGNETTE: false,
  76925. VIGNETTEBLENDMODEMULTIPLY: false,
  76926. VIGNETTEBLENDMODEOPAQUE: false,
  76927. TONEMAPPING: false,
  76928. CONTRAST: false,
  76929. COLORCURVES: false,
  76930. COLORGRADING: false,
  76931. COLORGRADING3D: false,
  76932. FROMLINEARSPACE: false,
  76933. SAMPLER3DGREENDEPTH: false,
  76934. SAMPLER3DBGRMAP: false,
  76935. IMAGEPROCESSINGPOSTPROCESS: false,
  76936. EXPOSURE: false,
  76937. };
  76938. // Setup the configuration as forced by the constructor. This would then not force the
  76939. // scene materials output in linear space and let untouched the default forward pass.
  76940. if (imageProcessingConfiguration) {
  76941. imageProcessingConfiguration.applyByPostProcess = true;
  76942. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76943. // This will cause the shader to be compiled
  76944. _this.fromLinearSpace = false;
  76945. }
  76946. // Setup the default processing configuration to the scene.
  76947. else {
  76948. _this._attachImageProcessingConfiguration(null, true);
  76949. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76950. }
  76951. _this.onApply = function (effect) {
  76952. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76953. };
  76954. return _this;
  76955. }
  76956. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76957. /**
  76958. * Gets the image processing configuration used either in this material.
  76959. */
  76960. get: function () {
  76961. return this._imageProcessingConfiguration;
  76962. },
  76963. /**
  76964. * Sets the Default image processing configuration used either in the this material.
  76965. *
  76966. * If sets to null, the scene one is in use.
  76967. */
  76968. set: function (value) {
  76969. this._attachImageProcessingConfiguration(value);
  76970. },
  76971. enumerable: true,
  76972. configurable: true
  76973. });
  76974. /**
  76975. * Attaches a new image processing configuration to the PBR Material.
  76976. * @param configuration
  76977. */
  76978. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76979. var _this = this;
  76980. if (doNotBuild === void 0) { doNotBuild = false; }
  76981. if (configuration === this._imageProcessingConfiguration) {
  76982. return;
  76983. }
  76984. // Detaches observer.
  76985. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76986. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76987. }
  76988. // Pick the scene configuration if needed.
  76989. if (!configuration) {
  76990. var scene = null;
  76991. var engine = this.getEngine();
  76992. var camera = this.getCamera();
  76993. if (camera) {
  76994. scene = camera.getScene();
  76995. }
  76996. else if (engine && engine.scenes) {
  76997. var scenes = engine.scenes;
  76998. scene = scenes[scenes.length - 1];
  76999. }
  77000. else {
  77001. scene = BABYLON.Engine.LastCreatedScene;
  77002. }
  77003. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77004. }
  77005. else {
  77006. this._imageProcessingConfiguration = configuration;
  77007. }
  77008. // Attaches observer.
  77009. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77010. _this._updateParameters();
  77011. });
  77012. // Ensure the effect will be rebuilt.
  77013. if (!doNotBuild) {
  77014. this._updateParameters();
  77015. }
  77016. };
  77017. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77018. /**
  77019. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77020. */
  77021. get: function () {
  77022. return this.imageProcessingConfiguration.colorCurves;
  77023. },
  77024. /**
  77025. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77026. */
  77027. set: function (value) {
  77028. this.imageProcessingConfiguration.colorCurves = value;
  77029. },
  77030. enumerable: true,
  77031. configurable: true
  77032. });
  77033. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77034. /**
  77035. * Gets wether the color curves effect is enabled.
  77036. */
  77037. get: function () {
  77038. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77039. },
  77040. /**
  77041. * Sets wether the color curves effect is enabled.
  77042. */
  77043. set: function (value) {
  77044. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77045. },
  77046. enumerable: true,
  77047. configurable: true
  77048. });
  77049. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77050. /**
  77051. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77052. */
  77053. get: function () {
  77054. return this.imageProcessingConfiguration.colorGradingTexture;
  77055. },
  77056. /**
  77057. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77058. */
  77059. set: function (value) {
  77060. this.imageProcessingConfiguration.colorGradingTexture = value;
  77061. },
  77062. enumerable: true,
  77063. configurable: true
  77064. });
  77065. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77066. /**
  77067. * Gets wether the color grading effect is enabled.
  77068. */
  77069. get: function () {
  77070. return this.imageProcessingConfiguration.colorGradingEnabled;
  77071. },
  77072. /**
  77073. * Gets wether the color grading effect is enabled.
  77074. */
  77075. set: function (value) {
  77076. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77077. },
  77078. enumerable: true,
  77079. configurable: true
  77080. });
  77081. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77082. /**
  77083. * Gets exposure used in the effect.
  77084. */
  77085. get: function () {
  77086. return this.imageProcessingConfiguration.exposure;
  77087. },
  77088. /**
  77089. * Sets exposure used in the effect.
  77090. */
  77091. set: function (value) {
  77092. this.imageProcessingConfiguration.exposure = value;
  77093. },
  77094. enumerable: true,
  77095. configurable: true
  77096. });
  77097. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77098. /**
  77099. * Gets wether tonemapping is enabled or not.
  77100. */
  77101. get: function () {
  77102. return this._imageProcessingConfiguration.toneMappingEnabled;
  77103. },
  77104. /**
  77105. * Sets wether tonemapping is enabled or not
  77106. */
  77107. set: function (value) {
  77108. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77109. },
  77110. enumerable: true,
  77111. configurable: true
  77112. });
  77113. ;
  77114. ;
  77115. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77116. /**
  77117. * Gets contrast used in the effect.
  77118. */
  77119. get: function () {
  77120. return this.imageProcessingConfiguration.contrast;
  77121. },
  77122. /**
  77123. * Sets contrast used in the effect.
  77124. */
  77125. set: function (value) {
  77126. this.imageProcessingConfiguration.contrast = value;
  77127. },
  77128. enumerable: true,
  77129. configurable: true
  77130. });
  77131. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77132. /**
  77133. * Gets Vignette stretch size.
  77134. */
  77135. get: function () {
  77136. return this.imageProcessingConfiguration.vignetteStretch;
  77137. },
  77138. /**
  77139. * Sets Vignette stretch size.
  77140. */
  77141. set: function (value) {
  77142. this.imageProcessingConfiguration.vignetteStretch = value;
  77143. },
  77144. enumerable: true,
  77145. configurable: true
  77146. });
  77147. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77148. /**
  77149. * Gets Vignette centre X Offset.
  77150. */
  77151. get: function () {
  77152. return this.imageProcessingConfiguration.vignetteCentreX;
  77153. },
  77154. /**
  77155. * Sets Vignette centre X Offset.
  77156. */
  77157. set: function (value) {
  77158. this.imageProcessingConfiguration.vignetteCentreX = value;
  77159. },
  77160. enumerable: true,
  77161. configurable: true
  77162. });
  77163. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77164. /**
  77165. * Gets Vignette centre Y Offset.
  77166. */
  77167. get: function () {
  77168. return this.imageProcessingConfiguration.vignetteCentreY;
  77169. },
  77170. /**
  77171. * Sets Vignette centre Y Offset.
  77172. */
  77173. set: function (value) {
  77174. this.imageProcessingConfiguration.vignetteCentreY = value;
  77175. },
  77176. enumerable: true,
  77177. configurable: true
  77178. });
  77179. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77180. /**
  77181. * Gets Vignette weight or intensity of the vignette effect.
  77182. */
  77183. get: function () {
  77184. return this.imageProcessingConfiguration.vignetteWeight;
  77185. },
  77186. /**
  77187. * Sets Vignette weight or intensity of the vignette effect.
  77188. */
  77189. set: function (value) {
  77190. this.imageProcessingConfiguration.vignetteWeight = value;
  77191. },
  77192. enumerable: true,
  77193. configurable: true
  77194. });
  77195. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77196. /**
  77197. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77198. * if vignetteEnabled is set to true.
  77199. */
  77200. get: function () {
  77201. return this.imageProcessingConfiguration.vignetteColor;
  77202. },
  77203. /**
  77204. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77205. * if vignetteEnabled is set to true.
  77206. */
  77207. set: function (value) {
  77208. this.imageProcessingConfiguration.vignetteColor = value;
  77209. },
  77210. enumerable: true,
  77211. configurable: true
  77212. });
  77213. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77214. /**
  77215. * Gets Camera field of view used by the Vignette effect.
  77216. */
  77217. get: function () {
  77218. return this.imageProcessingConfiguration.vignetteCameraFov;
  77219. },
  77220. /**
  77221. * Sets Camera field of view used by the Vignette effect.
  77222. */
  77223. set: function (value) {
  77224. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77225. },
  77226. enumerable: true,
  77227. configurable: true
  77228. });
  77229. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77230. /**
  77231. * Gets the vignette blend mode allowing different kind of effect.
  77232. */
  77233. get: function () {
  77234. return this.imageProcessingConfiguration.vignetteBlendMode;
  77235. },
  77236. /**
  77237. * Sets the vignette blend mode allowing different kind of effect.
  77238. */
  77239. set: function (value) {
  77240. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77241. },
  77242. enumerable: true,
  77243. configurable: true
  77244. });
  77245. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77246. /**
  77247. * Gets wether the vignette effect is enabled.
  77248. */
  77249. get: function () {
  77250. return this.imageProcessingConfiguration.vignetteEnabled;
  77251. },
  77252. /**
  77253. * Sets wether the vignette effect is enabled.
  77254. */
  77255. set: function (value) {
  77256. this.imageProcessingConfiguration.vignetteEnabled = value;
  77257. },
  77258. enumerable: true,
  77259. configurable: true
  77260. });
  77261. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77262. /**
  77263. * Gets wether the input of the processing is in Gamma or Linear Space.
  77264. */
  77265. get: function () {
  77266. return this._fromLinearSpace;
  77267. },
  77268. /**
  77269. * Sets wether the input of the processing is in Gamma or Linear Space.
  77270. */
  77271. set: function (value) {
  77272. if (this._fromLinearSpace === value) {
  77273. return;
  77274. }
  77275. this._fromLinearSpace = value;
  77276. this._updateParameters();
  77277. },
  77278. enumerable: true,
  77279. configurable: true
  77280. });
  77281. ImageProcessingPostProcess.prototype.getClassName = function () {
  77282. return "ImageProcessingPostProcess";
  77283. };
  77284. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77285. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77286. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77287. var defines = "";
  77288. for (var define in this._defines) {
  77289. if (this._defines[define]) {
  77290. defines += "#define " + define + ";\r\n";
  77291. }
  77292. }
  77293. var samplers = ["textureSampler"];
  77294. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77295. var uniforms = ["scale"];
  77296. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77297. this.updateEffect(defines, uniforms, samplers);
  77298. };
  77299. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77300. _super.prototype.dispose.call(this, camera);
  77301. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77302. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77303. }
  77304. this.imageProcessingConfiguration.applyByPostProcess = false;
  77305. };
  77306. __decorate([
  77307. BABYLON.serialize()
  77308. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77309. return ImageProcessingPostProcess;
  77310. }(BABYLON.PostProcess));
  77311. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77312. })(BABYLON || (BABYLON = {}));
  77313. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77314. var BABYLON;
  77315. (function (BABYLON) {
  77316. /**
  77317. * Class used to store bone information
  77318. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77319. */
  77320. var Bone = /** @class */ (function (_super) {
  77321. __extends(Bone, _super);
  77322. /**
  77323. * Create a new bone
  77324. * @param name defines the bone name
  77325. * @param skeleton defines the parent skeleton
  77326. * @param parentBone defines the parent (can be null if the bone is the root)
  77327. * @param localMatrix defines the local matrix
  77328. * @param restPose defines the rest pose matrix
  77329. * @param baseMatrix defines the base matrix
  77330. * @param index defines index of the bone in the hiearchy
  77331. */
  77332. function Bone(
  77333. /**
  77334. * defines the bone name
  77335. */
  77336. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77337. if (parentBone === void 0) { parentBone = null; }
  77338. if (localMatrix === void 0) { localMatrix = null; }
  77339. if (restPose === void 0) { restPose = null; }
  77340. if (baseMatrix === void 0) { baseMatrix = null; }
  77341. if (index === void 0) { index = null; }
  77342. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77343. _this.name = name;
  77344. /**
  77345. * Gets the list of child bones
  77346. */
  77347. _this.children = new Array();
  77348. /** Gets the animations associated with this bone */
  77349. _this.animations = new Array();
  77350. /**
  77351. * @hidden Internal only
  77352. * Set this value to map this bone to a different index in the transform matrices
  77353. * Set this value to -1 to exclude the bone from the transform matrices
  77354. */
  77355. _this._index = null;
  77356. _this._absoluteTransform = new BABYLON.Matrix();
  77357. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77358. _this._scalingDeterminant = 1;
  77359. _this._worldTransform = new BABYLON.Matrix();
  77360. _this._needToDecompose = true;
  77361. _this._needToCompose = false;
  77362. _this._skeleton = skeleton;
  77363. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77364. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77365. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77366. _this._index = index;
  77367. skeleton.bones.push(_this);
  77368. _this.setParent(parentBone, false);
  77369. if (baseMatrix || localMatrix) {
  77370. _this._updateDifferenceMatrix();
  77371. }
  77372. return _this;
  77373. }
  77374. Object.defineProperty(Bone.prototype, "_matrix", {
  77375. /** @hidden */
  77376. get: function () {
  77377. this._compose();
  77378. return this._localMatrix;
  77379. },
  77380. /** @hidden */
  77381. set: function (value) {
  77382. this._localMatrix.copyFrom(value);
  77383. this._needToDecompose = true;
  77384. },
  77385. enumerable: true,
  77386. configurable: true
  77387. });
  77388. // Members
  77389. /**
  77390. * Gets the parent skeleton
  77391. * @returns a skeleton
  77392. */
  77393. Bone.prototype.getSkeleton = function () {
  77394. return this._skeleton;
  77395. };
  77396. /**
  77397. * Gets parent bone
  77398. * @returns a bone or null if the bone is the root of the bone hierarchy
  77399. */
  77400. Bone.prototype.getParent = function () {
  77401. return this._parent;
  77402. };
  77403. /**
  77404. * Sets the parent bone
  77405. * @param parent defines the parent (can be null if the bone is the root)
  77406. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77407. */
  77408. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77409. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77410. if (this._parent === parent) {
  77411. return;
  77412. }
  77413. if (this._parent) {
  77414. var index = this._parent.children.indexOf(this);
  77415. if (index !== -1) {
  77416. this._parent.children.splice(index, 1);
  77417. }
  77418. }
  77419. this._parent = parent;
  77420. if (this._parent) {
  77421. this._parent.children.push(this);
  77422. }
  77423. if (updateDifferenceMatrix) {
  77424. this._updateDifferenceMatrix();
  77425. }
  77426. this.markAsDirty();
  77427. };
  77428. /**
  77429. * Gets the local matrix
  77430. * @returns a matrix
  77431. */
  77432. Bone.prototype.getLocalMatrix = function () {
  77433. this._compose();
  77434. return this._localMatrix;
  77435. };
  77436. /**
  77437. * Gets the base matrix (initial matrix which remains unchanged)
  77438. * @returns a matrix
  77439. */
  77440. Bone.prototype.getBaseMatrix = function () {
  77441. return this._baseMatrix;
  77442. };
  77443. /**
  77444. * Gets the rest pose matrix
  77445. * @returns a matrix
  77446. */
  77447. Bone.prototype.getRestPose = function () {
  77448. return this._restPose;
  77449. };
  77450. /**
  77451. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77452. */
  77453. Bone.prototype.getWorldMatrix = function () {
  77454. return this._worldTransform;
  77455. };
  77456. /**
  77457. * Sets the local matrix to rest pose matrix
  77458. */
  77459. Bone.prototype.returnToRest = function () {
  77460. this.updateMatrix(this._restPose.clone());
  77461. };
  77462. /**
  77463. * Gets the inverse of the absolute transform matrix.
  77464. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77465. * @returns a matrix
  77466. */
  77467. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77468. return this._invertedAbsoluteTransform;
  77469. };
  77470. /**
  77471. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77472. * @returns a matrix
  77473. */
  77474. Bone.prototype.getAbsoluteTransform = function () {
  77475. return this._absoluteTransform;
  77476. };
  77477. Object.defineProperty(Bone.prototype, "position", {
  77478. // Properties (matches AbstractMesh properties)
  77479. /** Gets or sets current position (in local space) */
  77480. get: function () {
  77481. this._decompose();
  77482. return this._localPosition;
  77483. },
  77484. set: function (newPosition) {
  77485. this._decompose();
  77486. this._localPosition.copyFrom(newPosition);
  77487. this._markAsDirtyAndCompose();
  77488. },
  77489. enumerable: true,
  77490. configurable: true
  77491. });
  77492. Object.defineProperty(Bone.prototype, "rotation", {
  77493. /** Gets or sets current rotation (in local space) */
  77494. get: function () {
  77495. return this.getRotation();
  77496. },
  77497. set: function (newRotation) {
  77498. this.setRotation(newRotation);
  77499. },
  77500. enumerable: true,
  77501. configurable: true
  77502. });
  77503. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77504. /** Gets or sets current rotation quaternion (in local space) */
  77505. get: function () {
  77506. this._decompose();
  77507. return this._localRotation;
  77508. },
  77509. set: function (newRotation) {
  77510. this.setRotationQuaternion(newRotation);
  77511. },
  77512. enumerable: true,
  77513. configurable: true
  77514. });
  77515. Object.defineProperty(Bone.prototype, "scaling", {
  77516. /** Gets or sets current scaling (in local space) */
  77517. get: function () {
  77518. return this.getScale();
  77519. },
  77520. set: function (newScaling) {
  77521. this.setScale(newScaling);
  77522. },
  77523. enumerable: true,
  77524. configurable: true
  77525. });
  77526. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77527. /**
  77528. * Gets the animation properties override
  77529. */
  77530. get: function () {
  77531. return this._skeleton.animationPropertiesOverride;
  77532. },
  77533. enumerable: true,
  77534. configurable: true
  77535. });
  77536. // Methods
  77537. Bone.prototype._decompose = function () {
  77538. if (!this._needToDecompose) {
  77539. return;
  77540. }
  77541. this._needToDecompose = false;
  77542. if (!this._localScaling) {
  77543. this._localScaling = BABYLON.Vector3.Zero();
  77544. this._localRotation = BABYLON.Quaternion.Zero();
  77545. this._localPosition = BABYLON.Vector3.Zero();
  77546. }
  77547. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77548. };
  77549. Bone.prototype._compose = function () {
  77550. if (!this._needToCompose) {
  77551. return;
  77552. }
  77553. this._needToCompose = false;
  77554. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77555. };
  77556. /**
  77557. * Update the base and local matrices
  77558. * @param matrix defines the new base or local matrix
  77559. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77560. * @param updateLocalMatrix defines if the local matrix should be updated
  77561. */
  77562. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77563. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77564. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77565. this._baseMatrix.copyFrom(matrix);
  77566. if (updateDifferenceMatrix) {
  77567. this._updateDifferenceMatrix();
  77568. }
  77569. if (updateLocalMatrix) {
  77570. this._localMatrix.copyFrom(matrix);
  77571. this._markAsDirtyAndDecompose();
  77572. }
  77573. else {
  77574. this.markAsDirty();
  77575. }
  77576. };
  77577. /** @hidden */
  77578. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77579. if (updateChildren === void 0) { updateChildren = true; }
  77580. if (!rootMatrix) {
  77581. rootMatrix = this._baseMatrix;
  77582. }
  77583. if (this._parent) {
  77584. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77585. }
  77586. else {
  77587. this._absoluteTransform.copyFrom(rootMatrix);
  77588. }
  77589. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77590. if (updateChildren) {
  77591. for (var index = 0; index < this.children.length; index++) {
  77592. this.children[index]._updateDifferenceMatrix();
  77593. }
  77594. }
  77595. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77596. };
  77597. /**
  77598. * Flag the bone as dirty (Forcing it to update everything)
  77599. */
  77600. Bone.prototype.markAsDirty = function () {
  77601. this._currentRenderId++;
  77602. this._childRenderId++;
  77603. this._skeleton._markAsDirty();
  77604. };
  77605. Bone.prototype._markAsDirtyAndCompose = function () {
  77606. this.markAsDirty();
  77607. this._needToCompose = true;
  77608. };
  77609. Bone.prototype._markAsDirtyAndDecompose = function () {
  77610. this.markAsDirty();
  77611. this._needToDecompose = true;
  77612. };
  77613. /**
  77614. * Copy an animation range from another bone
  77615. * @param source defines the source bone
  77616. * @param rangeName defines the range name to copy
  77617. * @param frameOffset defines the frame offset
  77618. * @param rescaleAsRequired defines if rescaling must be applied if required
  77619. * @param skelDimensionsRatio defines the scaling ratio
  77620. * @returns true if operation was successful
  77621. */
  77622. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77623. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77624. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77625. // all animation may be coming from a library skeleton, so may need to create animation
  77626. if (this.animations.length === 0) {
  77627. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77628. this.animations[0].setKeys([]);
  77629. }
  77630. // get animation info / verify there is such a range from the source bone
  77631. var sourceRange = source.animations[0].getRange(rangeName);
  77632. if (!sourceRange) {
  77633. return false;
  77634. }
  77635. var from = sourceRange.from;
  77636. var to = sourceRange.to;
  77637. var sourceKeys = source.animations[0].getKeys();
  77638. // rescaling prep
  77639. var sourceBoneLength = source.length;
  77640. var sourceParent = source.getParent();
  77641. var parent = this.getParent();
  77642. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77643. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77644. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77645. var destKeys = this.animations[0].getKeys();
  77646. // loop vars declaration
  77647. var orig;
  77648. var origTranslation;
  77649. var mat;
  77650. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77651. orig = sourceKeys[key];
  77652. if (orig.frame >= from && orig.frame <= to) {
  77653. if (rescaleAsRequired) {
  77654. mat = orig.value.clone();
  77655. // scale based on parent ratio, when bone has parent
  77656. if (parentScalingReqd) {
  77657. origTranslation = mat.getTranslation();
  77658. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77659. // scale based on skeleton dimension ratio when root bone, and value is passed
  77660. }
  77661. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77662. origTranslation = mat.getTranslation();
  77663. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77664. // use original when root bone, and no data for skelDimensionsRatio
  77665. }
  77666. else {
  77667. mat = orig.value;
  77668. }
  77669. }
  77670. else {
  77671. mat = orig.value;
  77672. }
  77673. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77674. }
  77675. }
  77676. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77677. return true;
  77678. };
  77679. /**
  77680. * Translate the bone in local or world space
  77681. * @param vec The amount to translate the bone
  77682. * @param space The space that the translation is in
  77683. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77684. */
  77685. Bone.prototype.translate = function (vec, space, mesh) {
  77686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77687. var lm = this.getLocalMatrix();
  77688. if (space == BABYLON.Space.LOCAL) {
  77689. lm.m[12] += vec.x;
  77690. lm.m[13] += vec.y;
  77691. lm.m[14] += vec.z;
  77692. }
  77693. else {
  77694. var wm = null;
  77695. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77696. if (mesh) {
  77697. wm = mesh.getWorldMatrix();
  77698. }
  77699. this._skeleton.computeAbsoluteTransforms();
  77700. var tmat = Bone._tmpMats[0];
  77701. var tvec = Bone._tmpVecs[0];
  77702. if (this._parent) {
  77703. if (mesh && wm) {
  77704. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77705. tmat.multiplyToRef(wm, tmat);
  77706. }
  77707. else {
  77708. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77709. }
  77710. }
  77711. tmat.m[12] = 0;
  77712. tmat.m[13] = 0;
  77713. tmat.m[14] = 0;
  77714. tmat.invert();
  77715. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77716. lm.m[12] += tvec.x;
  77717. lm.m[13] += tvec.y;
  77718. lm.m[14] += tvec.z;
  77719. }
  77720. this._markAsDirtyAndDecompose();
  77721. };
  77722. /**
  77723. * Set the postion of the bone in local or world space
  77724. * @param position The position to set the bone
  77725. * @param space The space that the position is in
  77726. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77727. */
  77728. Bone.prototype.setPosition = function (position, space, mesh) {
  77729. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77730. var lm = this.getLocalMatrix();
  77731. if (space == BABYLON.Space.LOCAL) {
  77732. lm.m[12] = position.x;
  77733. lm.m[13] = position.y;
  77734. lm.m[14] = position.z;
  77735. }
  77736. else {
  77737. var wm = null;
  77738. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77739. if (mesh) {
  77740. wm = mesh.getWorldMatrix();
  77741. }
  77742. this._skeleton.computeAbsoluteTransforms();
  77743. var tmat = Bone._tmpMats[0];
  77744. var vec = Bone._tmpVecs[0];
  77745. if (this._parent) {
  77746. if (mesh && wm) {
  77747. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77748. tmat.multiplyToRef(wm, tmat);
  77749. }
  77750. else {
  77751. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77752. }
  77753. }
  77754. tmat.invert();
  77755. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77756. lm.m[12] = vec.x;
  77757. lm.m[13] = vec.y;
  77758. lm.m[14] = vec.z;
  77759. }
  77760. this._markAsDirtyAndDecompose();
  77761. };
  77762. /**
  77763. * Set the absolute position of the bone (world space)
  77764. * @param position The position to set the bone
  77765. * @param mesh The mesh that this bone is attached to
  77766. */
  77767. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77768. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77769. };
  77770. /**
  77771. * Scale the bone on the x, y and z axes (in local space)
  77772. * @param x The amount to scale the bone on the x axis
  77773. * @param y The amount to scale the bone on the y axis
  77774. * @param z The amount to scale the bone on the z axis
  77775. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77776. */
  77777. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77778. if (scaleChildren === void 0) { scaleChildren = false; }
  77779. var locMat = this.getLocalMatrix();
  77780. // Apply new scaling on top of current local matrix
  77781. var scaleMat = Bone._tmpMats[0];
  77782. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77783. scaleMat.multiplyToRef(locMat, locMat);
  77784. // Invert scaling matrix and apply the inverse to all children
  77785. scaleMat.invert();
  77786. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77787. var child = _a[_i];
  77788. var cm = child.getLocalMatrix();
  77789. cm.multiplyToRef(scaleMat, cm);
  77790. cm.m[12] *= x;
  77791. cm.m[13] *= y;
  77792. cm.m[14] *= z;
  77793. child._markAsDirtyAndDecompose();
  77794. }
  77795. this._markAsDirtyAndDecompose();
  77796. if (scaleChildren) {
  77797. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77798. var child = _c[_b];
  77799. child.scale(x, y, z, scaleChildren);
  77800. }
  77801. }
  77802. };
  77803. /**
  77804. * Set the bone scaling in local space
  77805. * @param scale defines the scaling vector
  77806. */
  77807. Bone.prototype.setScale = function (scale) {
  77808. this._decompose();
  77809. this._localScaling.copyFrom(scale);
  77810. this._markAsDirtyAndCompose();
  77811. };
  77812. /**
  77813. * Gets the current scaling in local space
  77814. * @returns the current scaling vector
  77815. */
  77816. Bone.prototype.getScale = function () {
  77817. this._decompose();
  77818. return this._localScaling;
  77819. };
  77820. /**
  77821. * Gets the current scaling in local space and stores it in a target vector
  77822. * @param result defines the target vector
  77823. */
  77824. Bone.prototype.getScaleToRef = function (result) {
  77825. this._decompose();
  77826. result.copyFrom(this._localScaling);
  77827. };
  77828. /**
  77829. * Set the yaw, pitch, and roll of the bone in local or world space
  77830. * @param yaw The rotation of the bone on the y axis
  77831. * @param pitch The rotation of the bone on the x axis
  77832. * @param roll The rotation of the bone on the z axis
  77833. * @param space The space that the axes of rotation are in
  77834. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77835. */
  77836. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77837. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77838. if (space === BABYLON.Space.LOCAL) {
  77839. var quat = Bone._tmpQuat;
  77840. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77841. this.setRotationQuaternion(quat, space, mesh);
  77842. return;
  77843. }
  77844. var rotMatInv = Bone._tmpMats[0];
  77845. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77846. return;
  77847. }
  77848. var rotMat = Bone._tmpMats[1];
  77849. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77850. rotMatInv.multiplyToRef(rotMat, rotMat);
  77851. this._rotateWithMatrix(rotMat, space, mesh);
  77852. };
  77853. /**
  77854. * Add a rotation to the bone on an axis in local or world space
  77855. * @param axis The axis to rotate the bone on
  77856. * @param amount The amount to rotate the bone
  77857. * @param space The space that the axis is in
  77858. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77859. */
  77860. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77861. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77862. var rmat = Bone._tmpMats[0];
  77863. rmat.m[12] = 0;
  77864. rmat.m[13] = 0;
  77865. rmat.m[14] = 0;
  77866. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77867. this._rotateWithMatrix(rmat, space, mesh);
  77868. };
  77869. /**
  77870. * Set the rotation of the bone to a particular axis angle in local or world space
  77871. * @param axis The axis to rotate the bone on
  77872. * @param angle The angle that the bone should be rotated to
  77873. * @param space The space that the axis is in
  77874. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77875. */
  77876. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77877. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77878. if (space === BABYLON.Space.LOCAL) {
  77879. var quat = Bone._tmpQuat;
  77880. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77881. this.setRotationQuaternion(quat, space, mesh);
  77882. return;
  77883. }
  77884. var rotMatInv = Bone._tmpMats[0];
  77885. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77886. return;
  77887. }
  77888. var rotMat = Bone._tmpMats[1];
  77889. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77890. rotMatInv.multiplyToRef(rotMat, rotMat);
  77891. this._rotateWithMatrix(rotMat, space, mesh);
  77892. };
  77893. /**
  77894. * Set the euler rotation of the bone in local of world space
  77895. * @param rotation The euler rotation that the bone should be set to
  77896. * @param space The space that the rotation is in
  77897. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77898. */
  77899. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77901. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77902. };
  77903. /**
  77904. * Set the quaternion rotation of the bone in local of world space
  77905. * @param quat The quaternion rotation that the bone should be set to
  77906. * @param space The space that the rotation is in
  77907. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77908. */
  77909. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77911. if (space === BABYLON.Space.LOCAL) {
  77912. this._decompose();
  77913. this._localRotation.copyFrom(quat);
  77914. this._markAsDirtyAndCompose();
  77915. return;
  77916. }
  77917. var rotMatInv = Bone._tmpMats[0];
  77918. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77919. return;
  77920. }
  77921. var rotMat = Bone._tmpMats[1];
  77922. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77923. rotMatInv.multiplyToRef(rotMat, rotMat);
  77924. this._rotateWithMatrix(rotMat, space, mesh);
  77925. };
  77926. /**
  77927. * Set the rotation matrix of the bone in local of world space
  77928. * @param rotMat The rotation matrix that the bone should be set to
  77929. * @param space The space that the rotation is in
  77930. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77931. */
  77932. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77934. if (space === BABYLON.Space.LOCAL) {
  77935. var quat = Bone._tmpQuat;
  77936. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77937. this.setRotationQuaternion(quat, space, mesh);
  77938. return;
  77939. }
  77940. var rotMatInv = Bone._tmpMats[0];
  77941. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77942. return;
  77943. }
  77944. var rotMat2 = Bone._tmpMats[1];
  77945. rotMat2.copyFrom(rotMat);
  77946. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77947. this._rotateWithMatrix(rotMat2, space, mesh);
  77948. };
  77949. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77951. var lmat = this.getLocalMatrix();
  77952. var lx = lmat.m[12];
  77953. var ly = lmat.m[13];
  77954. var lz = lmat.m[14];
  77955. var parent = this.getParent();
  77956. var parentScale = Bone._tmpMats[3];
  77957. var parentScaleInv = Bone._tmpMats[4];
  77958. if (parent && space == BABYLON.Space.WORLD) {
  77959. if (mesh) {
  77960. parentScale.copyFrom(mesh.getWorldMatrix());
  77961. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77962. }
  77963. else {
  77964. parentScale.copyFrom(parent.getAbsoluteTransform());
  77965. }
  77966. parentScaleInv.copyFrom(parentScale);
  77967. parentScaleInv.invert();
  77968. lmat.multiplyToRef(parentScale, lmat);
  77969. lmat.multiplyToRef(rmat, lmat);
  77970. lmat.multiplyToRef(parentScaleInv, lmat);
  77971. }
  77972. else {
  77973. if (space == BABYLON.Space.WORLD && mesh) {
  77974. parentScale.copyFrom(mesh.getWorldMatrix());
  77975. parentScaleInv.copyFrom(parentScale);
  77976. parentScaleInv.invert();
  77977. lmat.multiplyToRef(parentScale, lmat);
  77978. lmat.multiplyToRef(rmat, lmat);
  77979. lmat.multiplyToRef(parentScaleInv, lmat);
  77980. }
  77981. else {
  77982. lmat.multiplyToRef(rmat, lmat);
  77983. }
  77984. }
  77985. lmat.m[12] = lx;
  77986. lmat.m[13] = ly;
  77987. lmat.m[14] = lz;
  77988. this.computeAbsoluteTransforms();
  77989. this._markAsDirtyAndDecompose();
  77990. };
  77991. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77992. var scaleMatrix = Bone._tmpMats[2];
  77993. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77994. if (mesh) {
  77995. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77996. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77997. }
  77998. rotMatInv.invert();
  77999. if (isNaN(rotMatInv.m[0])) {
  78000. // Matrix failed to invert.
  78001. // This can happen if scale is zero for example.
  78002. return false;
  78003. }
  78004. scaleMatrix.m[0] *= this._scalingDeterminant;
  78005. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78006. return true;
  78007. };
  78008. /**
  78009. * Get the position of the bone in local or world space
  78010. * @param space The space that the returned position is in
  78011. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78012. * @returns The position of the bone
  78013. */
  78014. Bone.prototype.getPosition = function (space, mesh) {
  78015. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78016. if (mesh === void 0) { mesh = null; }
  78017. var pos = BABYLON.Vector3.Zero();
  78018. this.getPositionToRef(space, mesh, pos);
  78019. return pos;
  78020. };
  78021. /**
  78022. * Copy the position of the bone to a vector3 in local or world space
  78023. * @param space The space that the returned position is in
  78024. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78025. * @param result The vector3 to copy the position to
  78026. */
  78027. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78028. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78029. if (space == BABYLON.Space.LOCAL) {
  78030. var lm = this.getLocalMatrix();
  78031. result.x = lm.m[12];
  78032. result.y = lm.m[13];
  78033. result.z = lm.m[14];
  78034. }
  78035. else {
  78036. var wm = null;
  78037. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78038. if (mesh) {
  78039. wm = mesh.getWorldMatrix();
  78040. }
  78041. this._skeleton.computeAbsoluteTransforms();
  78042. var tmat = Bone._tmpMats[0];
  78043. if (mesh && wm) {
  78044. tmat.copyFrom(this.getAbsoluteTransform());
  78045. tmat.multiplyToRef(wm, tmat);
  78046. }
  78047. else {
  78048. tmat = this.getAbsoluteTransform();
  78049. }
  78050. result.x = tmat.m[12];
  78051. result.y = tmat.m[13];
  78052. result.z = tmat.m[14];
  78053. }
  78054. };
  78055. /**
  78056. * Get the absolute position of the bone (world space)
  78057. * @param mesh The mesh that this bone is attached to
  78058. * @returns The absolute position of the bone
  78059. */
  78060. Bone.prototype.getAbsolutePosition = function (mesh) {
  78061. if (mesh === void 0) { mesh = null; }
  78062. var pos = BABYLON.Vector3.Zero();
  78063. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78064. return pos;
  78065. };
  78066. /**
  78067. * Copy the absolute position of the bone (world space) to the result param
  78068. * @param mesh The mesh that this bone is attached to
  78069. * @param result The vector3 to copy the absolute position to
  78070. */
  78071. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78072. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78073. };
  78074. /**
  78075. * Compute the absolute transforms of this bone and its children
  78076. */
  78077. Bone.prototype.computeAbsoluteTransforms = function () {
  78078. this._compose();
  78079. if (this._parent) {
  78080. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78081. }
  78082. else {
  78083. this._absoluteTransform.copyFrom(this._localMatrix);
  78084. var poseMatrix = this._skeleton.getPoseMatrix();
  78085. if (poseMatrix) {
  78086. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78087. }
  78088. }
  78089. var children = this.children;
  78090. var len = children.length;
  78091. for (var i = 0; i < len; i++) {
  78092. children[i].computeAbsoluteTransforms();
  78093. }
  78094. };
  78095. /**
  78096. * Get the world direction from an axis that is in the local space of the bone
  78097. * @param localAxis The local direction that is used to compute the world direction
  78098. * @param mesh The mesh that this bone is attached to
  78099. * @returns The world direction
  78100. */
  78101. Bone.prototype.getDirection = function (localAxis, mesh) {
  78102. if (mesh === void 0) { mesh = null; }
  78103. var result = BABYLON.Vector3.Zero();
  78104. this.getDirectionToRef(localAxis, mesh, result);
  78105. return result;
  78106. };
  78107. /**
  78108. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78109. * @param localAxis The local direction that is used to compute the world direction
  78110. * @param mesh The mesh that this bone is attached to
  78111. * @param result The vector3 that the world direction will be copied to
  78112. */
  78113. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78114. if (mesh === void 0) { mesh = null; }
  78115. var wm = null;
  78116. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78117. if (mesh) {
  78118. wm = mesh.getWorldMatrix();
  78119. }
  78120. this._skeleton.computeAbsoluteTransforms();
  78121. var mat = Bone._tmpMats[0];
  78122. mat.copyFrom(this.getAbsoluteTransform());
  78123. if (mesh && wm) {
  78124. mat.multiplyToRef(wm, mat);
  78125. }
  78126. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78127. result.normalize();
  78128. };
  78129. /**
  78130. * Get the euler rotation of the bone in local or world space
  78131. * @param space The space that the rotation should be in
  78132. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78133. * @returns The euler rotation
  78134. */
  78135. Bone.prototype.getRotation = function (space, mesh) {
  78136. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78137. if (mesh === void 0) { mesh = null; }
  78138. var result = BABYLON.Vector3.Zero();
  78139. this.getRotationToRef(space, mesh, result);
  78140. return result;
  78141. };
  78142. /**
  78143. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78144. * @param space The space that the rotation should be in
  78145. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78146. * @param result The vector3 that the rotation should be copied to
  78147. */
  78148. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78150. if (mesh === void 0) { mesh = null; }
  78151. var quat = Bone._tmpQuat;
  78152. this.getRotationQuaternionToRef(space, mesh, quat);
  78153. quat.toEulerAnglesToRef(result);
  78154. };
  78155. /**
  78156. * Get the quaternion rotation of the bone in either local or world space
  78157. * @param space The space that the rotation should be in
  78158. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78159. * @returns The quaternion rotation
  78160. */
  78161. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78163. if (mesh === void 0) { mesh = null; }
  78164. var result = BABYLON.Quaternion.Identity();
  78165. this.getRotationQuaternionToRef(space, mesh, result);
  78166. return result;
  78167. };
  78168. /**
  78169. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78170. * @param space The space that the rotation should be in
  78171. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78172. * @param result The quaternion that the rotation should be copied to
  78173. */
  78174. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78175. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78176. if (mesh === void 0) { mesh = null; }
  78177. if (space == BABYLON.Space.LOCAL) {
  78178. this._decompose();
  78179. result.copyFrom(this._localRotation);
  78180. }
  78181. else {
  78182. var mat = Bone._tmpMats[0];
  78183. var amat = this.getAbsoluteTransform();
  78184. if (mesh) {
  78185. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78186. }
  78187. else {
  78188. mat.copyFrom(amat);
  78189. }
  78190. mat.m[0] *= this._scalingDeterminant;
  78191. mat.m[1] *= this._scalingDeterminant;
  78192. mat.m[2] *= this._scalingDeterminant;
  78193. mat.decompose(undefined, result, undefined);
  78194. }
  78195. };
  78196. /**
  78197. * Get the rotation matrix of the bone in local or world space
  78198. * @param space The space that the rotation should be in
  78199. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78200. * @returns The rotation matrix
  78201. */
  78202. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78203. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78204. var result = BABYLON.Matrix.Identity();
  78205. this.getRotationMatrixToRef(space, mesh, result);
  78206. return result;
  78207. };
  78208. /**
  78209. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78210. * @param space The space that the rotation should be in
  78211. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78212. * @param result The quaternion that the rotation should be copied to
  78213. */
  78214. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78216. if (space == BABYLON.Space.LOCAL) {
  78217. this.getLocalMatrix().getRotationMatrixToRef(result);
  78218. }
  78219. else {
  78220. var mat = Bone._tmpMats[0];
  78221. var amat = this.getAbsoluteTransform();
  78222. if (mesh) {
  78223. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78224. }
  78225. else {
  78226. mat.copyFrom(amat);
  78227. }
  78228. mat.m[0] *= this._scalingDeterminant;
  78229. mat.m[1] *= this._scalingDeterminant;
  78230. mat.m[2] *= this._scalingDeterminant;
  78231. mat.getRotationMatrixToRef(result);
  78232. }
  78233. };
  78234. /**
  78235. * Get the world position of a point that is in the local space of the bone
  78236. * @param position The local position
  78237. * @param mesh The mesh that this bone is attached to
  78238. * @returns The world position
  78239. */
  78240. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78241. if (mesh === void 0) { mesh = null; }
  78242. var result = BABYLON.Vector3.Zero();
  78243. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78244. return result;
  78245. };
  78246. /**
  78247. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78248. * @param position The local position
  78249. * @param mesh The mesh that this bone is attached to
  78250. * @param result The vector3 that the world position should be copied to
  78251. */
  78252. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78253. if (mesh === void 0) { mesh = null; }
  78254. var wm = null;
  78255. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78256. if (mesh) {
  78257. wm = mesh.getWorldMatrix();
  78258. }
  78259. this._skeleton.computeAbsoluteTransforms();
  78260. var tmat = Bone._tmpMats[0];
  78261. if (mesh && wm) {
  78262. tmat.copyFrom(this.getAbsoluteTransform());
  78263. tmat.multiplyToRef(wm, tmat);
  78264. }
  78265. else {
  78266. tmat = this.getAbsoluteTransform();
  78267. }
  78268. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78269. };
  78270. /**
  78271. * Get the local position of a point that is in world space
  78272. * @param position The world position
  78273. * @param mesh The mesh that this bone is attached to
  78274. * @returns The local position
  78275. */
  78276. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78277. if (mesh === void 0) { mesh = null; }
  78278. var result = BABYLON.Vector3.Zero();
  78279. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78280. return result;
  78281. };
  78282. /**
  78283. * Get the local position of a point that is in world space and copy it to the result param
  78284. * @param position The world position
  78285. * @param mesh The mesh that this bone is attached to
  78286. * @param result The vector3 that the local position should be copied to
  78287. */
  78288. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78289. if (mesh === void 0) { mesh = null; }
  78290. var wm = null;
  78291. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78292. if (mesh) {
  78293. wm = mesh.getWorldMatrix();
  78294. }
  78295. this._skeleton.computeAbsoluteTransforms();
  78296. var tmat = Bone._tmpMats[0];
  78297. tmat.copyFrom(this.getAbsoluteTransform());
  78298. if (mesh && wm) {
  78299. tmat.multiplyToRef(wm, tmat);
  78300. }
  78301. tmat.invert();
  78302. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78303. };
  78304. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78305. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78306. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78307. return Bone;
  78308. }(BABYLON.Node));
  78309. BABYLON.Bone = Bone;
  78310. })(BABYLON || (BABYLON = {}));
  78311. //# sourceMappingURL=babylon.bone.js.map
  78312. var BABYLON;
  78313. (function (BABYLON) {
  78314. /**
  78315. * Class used to apply inverse kinematics to bones
  78316. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78317. */
  78318. var BoneIKController = /** @class */ (function () {
  78319. /**
  78320. * Creates a new BoneIKController
  78321. * @param mesh defines the mesh to control
  78322. * @param bone defines the bone to control
  78323. * @param options defines options to set up the controller
  78324. */
  78325. function BoneIKController(mesh, bone, options) {
  78326. /**
  78327. * Gets or sets the target position
  78328. */
  78329. this.targetPosition = BABYLON.Vector3.Zero();
  78330. /**
  78331. * Gets or sets the pole target position
  78332. */
  78333. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78334. /**
  78335. * Gets or sets the pole target local offset
  78336. */
  78337. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78338. /**
  78339. * Gets or sets the pole angle
  78340. */
  78341. this.poleAngle = 0;
  78342. /**
  78343. * 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)
  78344. */
  78345. this.slerpAmount = 1;
  78346. this._bone1Quat = BABYLON.Quaternion.Identity();
  78347. this._bone1Mat = BABYLON.Matrix.Identity();
  78348. this._bone2Ang = Math.PI;
  78349. this._maxAngle = Math.PI;
  78350. this._rightHandedSystem = false;
  78351. this._bendAxis = BABYLON.Vector3.Right();
  78352. this._slerping = false;
  78353. this._adjustRoll = 0;
  78354. this._bone2 = bone;
  78355. this._bone1 = bone.getParent();
  78356. if (!this._bone1) {
  78357. return;
  78358. }
  78359. this.mesh = mesh;
  78360. var bonePos = bone.getPosition();
  78361. if (bone.getAbsoluteTransform().determinant() > 0) {
  78362. this._rightHandedSystem = true;
  78363. this._bendAxis.x = 0;
  78364. this._bendAxis.y = 0;
  78365. this._bendAxis.z = -1;
  78366. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78367. this._adjustRoll = Math.PI * .5;
  78368. this._bendAxis.z = 1;
  78369. }
  78370. }
  78371. if (this._bone1.length) {
  78372. var boneScale1 = this._bone1.getScale();
  78373. var boneScale2 = this._bone2.getScale();
  78374. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78375. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78376. }
  78377. else if (this._bone1.children[0]) {
  78378. mesh.computeWorldMatrix(true);
  78379. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78380. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78381. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78382. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78383. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78384. }
  78385. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78386. this.maxAngle = Math.PI;
  78387. if (options) {
  78388. if (options.targetMesh) {
  78389. this.targetMesh = options.targetMesh;
  78390. this.targetMesh.computeWorldMatrix(true);
  78391. }
  78392. if (options.poleTargetMesh) {
  78393. this.poleTargetMesh = options.poleTargetMesh;
  78394. this.poleTargetMesh.computeWorldMatrix(true);
  78395. }
  78396. else if (options.poleTargetBone) {
  78397. this.poleTargetBone = options.poleTargetBone;
  78398. }
  78399. else if (this._bone1.getParent()) {
  78400. this.poleTargetBone = this._bone1.getParent();
  78401. }
  78402. if (options.poleTargetLocalOffset) {
  78403. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78404. }
  78405. if (options.poleAngle) {
  78406. this.poleAngle = options.poleAngle;
  78407. }
  78408. if (options.bendAxis) {
  78409. this._bendAxis.copyFrom(options.bendAxis);
  78410. }
  78411. if (options.maxAngle) {
  78412. this.maxAngle = options.maxAngle;
  78413. }
  78414. if (options.slerpAmount) {
  78415. this.slerpAmount = options.slerpAmount;
  78416. }
  78417. }
  78418. }
  78419. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78420. /**
  78421. * Gets or sets maximum allowed angle
  78422. */
  78423. get: function () {
  78424. return this._maxAngle;
  78425. },
  78426. set: function (value) {
  78427. this._setMaxAngle(value);
  78428. },
  78429. enumerable: true,
  78430. configurable: true
  78431. });
  78432. BoneIKController.prototype._setMaxAngle = function (ang) {
  78433. if (ang < 0) {
  78434. ang = 0;
  78435. }
  78436. if (ang > Math.PI || ang == undefined) {
  78437. ang = Math.PI;
  78438. }
  78439. this._maxAngle = ang;
  78440. var a = this._bone1Length;
  78441. var b = this._bone2Length;
  78442. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78443. };
  78444. /**
  78445. * Force the controller to update the bones
  78446. */
  78447. BoneIKController.prototype.update = function () {
  78448. var bone1 = this._bone1;
  78449. if (!bone1) {
  78450. return;
  78451. }
  78452. var target = this.targetPosition;
  78453. var poleTarget = this.poleTargetPosition;
  78454. var mat1 = BoneIKController._tmpMats[0];
  78455. var mat2 = BoneIKController._tmpMats[1];
  78456. if (this.targetMesh) {
  78457. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78458. }
  78459. if (this.poleTargetBone) {
  78460. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78461. }
  78462. else if (this.poleTargetMesh) {
  78463. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78464. }
  78465. var bonePos = BoneIKController._tmpVecs[0];
  78466. var zaxis = BoneIKController._tmpVecs[1];
  78467. var xaxis = BoneIKController._tmpVecs[2];
  78468. var yaxis = BoneIKController._tmpVecs[3];
  78469. var upAxis = BoneIKController._tmpVecs[4];
  78470. var _tmpQuat = BoneIKController._tmpQuat;
  78471. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78472. poleTarget.subtractToRef(bonePos, upAxis);
  78473. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78474. upAxis.y = 1;
  78475. }
  78476. else {
  78477. upAxis.normalize();
  78478. }
  78479. target.subtractToRef(bonePos, yaxis);
  78480. yaxis.normalize();
  78481. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78482. zaxis.normalize();
  78483. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78484. xaxis.normalize();
  78485. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78486. var a = this._bone1Length;
  78487. var b = this._bone2Length;
  78488. var c = BABYLON.Vector3.Distance(bonePos, target);
  78489. if (this._maxReach > 0) {
  78490. c = Math.min(this._maxReach, c);
  78491. }
  78492. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78493. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78494. if (acosa > 1) {
  78495. acosa = 1;
  78496. }
  78497. if (acosb > 1) {
  78498. acosb = 1;
  78499. }
  78500. if (acosa < -1) {
  78501. acosa = -1;
  78502. }
  78503. if (acosb < -1) {
  78504. acosb = -1;
  78505. }
  78506. var angA = Math.acos(acosa);
  78507. var angB = Math.acos(acosb);
  78508. var angC = -angA - angB;
  78509. if (this._rightHandedSystem) {
  78510. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78511. mat2.multiplyToRef(mat1, mat1);
  78512. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78513. mat2.multiplyToRef(mat1, mat1);
  78514. }
  78515. else {
  78516. var _tmpVec = BoneIKController._tmpVecs[5];
  78517. _tmpVec.copyFrom(this._bendAxis);
  78518. _tmpVec.x *= -1;
  78519. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78520. mat2.multiplyToRef(mat1, mat1);
  78521. }
  78522. if (this.poleAngle) {
  78523. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78524. mat1.multiplyToRef(mat2, mat1);
  78525. }
  78526. if (this._bone1) {
  78527. if (this.slerpAmount < 1) {
  78528. if (!this._slerping) {
  78529. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78530. }
  78531. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78532. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78533. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78534. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78535. this._slerping = true;
  78536. }
  78537. else {
  78538. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78539. this._bone1Mat.copyFrom(mat1);
  78540. this._slerping = false;
  78541. }
  78542. }
  78543. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78544. this._bone2Ang = angC;
  78545. };
  78546. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78547. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78548. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78549. return BoneIKController;
  78550. }());
  78551. BABYLON.BoneIKController = BoneIKController;
  78552. })(BABYLON || (BABYLON = {}));
  78553. //# sourceMappingURL=babylon.boneIKController.js.map
  78554. var BABYLON;
  78555. (function (BABYLON) {
  78556. /**
  78557. * Class used to make a bone look toward a point in space
  78558. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78559. */
  78560. var BoneLookController = /** @class */ (function () {
  78561. /**
  78562. * Create a BoneLookController
  78563. * @param mesh the mesh that the bone belongs to
  78564. * @param bone the bone that will be looking to the target
  78565. * @param target the target Vector3 to look at
  78566. * @param settings optional settings:
  78567. * * maxYaw: the maximum angle the bone will yaw to
  78568. * * minYaw: the minimum angle the bone will yaw to
  78569. * * maxPitch: the maximum angle the bone will pitch to
  78570. * * minPitch: the minimum angle the bone will yaw to
  78571. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78572. * * upAxis: the up axis of the coordinate system
  78573. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78574. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78575. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78576. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78577. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78578. * * adjustRoll: used to make an adjustment to the roll of the bone
  78579. **/
  78580. function BoneLookController(mesh, bone, target, options) {
  78581. /**
  78582. * The up axis of the coordinate system that is used when the bone is rotated
  78583. */
  78584. this.upAxis = BABYLON.Vector3.Up();
  78585. /**
  78586. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78587. */
  78588. this.upAxisSpace = BABYLON.Space.LOCAL;
  78589. /**
  78590. * Used to make an adjustment to the yaw of the bone
  78591. */
  78592. this.adjustYaw = 0;
  78593. /**
  78594. * Used to make an adjustment to the pitch of the bone
  78595. */
  78596. this.adjustPitch = 0;
  78597. /**
  78598. * Used to make an adjustment to the roll of the bone
  78599. */
  78600. this.adjustRoll = 0;
  78601. /**
  78602. * 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)
  78603. */
  78604. this.slerpAmount = 1;
  78605. this._boneQuat = BABYLON.Quaternion.Identity();
  78606. this._slerping = false;
  78607. this._firstFrameSkipped = false;
  78608. this._fowardAxis = BABYLON.Vector3.Forward();
  78609. this.mesh = mesh;
  78610. this.bone = bone;
  78611. this.target = target;
  78612. if (options) {
  78613. if (options.adjustYaw) {
  78614. this.adjustYaw = options.adjustYaw;
  78615. }
  78616. if (options.adjustPitch) {
  78617. this.adjustPitch = options.adjustPitch;
  78618. }
  78619. if (options.adjustRoll) {
  78620. this.adjustRoll = options.adjustRoll;
  78621. }
  78622. if (options.maxYaw != null) {
  78623. this.maxYaw = options.maxYaw;
  78624. }
  78625. else {
  78626. this.maxYaw = Math.PI;
  78627. }
  78628. if (options.minYaw != null) {
  78629. this.minYaw = options.minYaw;
  78630. }
  78631. else {
  78632. this.minYaw = -Math.PI;
  78633. }
  78634. if (options.maxPitch != null) {
  78635. this.maxPitch = options.maxPitch;
  78636. }
  78637. else {
  78638. this.maxPitch = Math.PI;
  78639. }
  78640. if (options.minPitch != null) {
  78641. this.minPitch = options.minPitch;
  78642. }
  78643. else {
  78644. this.minPitch = -Math.PI;
  78645. }
  78646. if (options.slerpAmount != null) {
  78647. this.slerpAmount = options.slerpAmount;
  78648. }
  78649. if (options.upAxis != null) {
  78650. this.upAxis = options.upAxis;
  78651. }
  78652. if (options.upAxisSpace != null) {
  78653. this.upAxisSpace = options.upAxisSpace;
  78654. }
  78655. if (options.yawAxis != null || options.pitchAxis != null) {
  78656. var newYawAxis = BABYLON.Axis.Y;
  78657. var newPitchAxis = BABYLON.Axis.X;
  78658. if (options.yawAxis != null) {
  78659. newYawAxis = options.yawAxis.clone();
  78660. newYawAxis.normalize();
  78661. }
  78662. if (options.pitchAxis != null) {
  78663. newPitchAxis = options.pitchAxis.clone();
  78664. newPitchAxis.normalize();
  78665. }
  78666. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78667. this._transformYawPitch = BABYLON.Matrix.Identity();
  78668. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78669. this._transformYawPitchInv = this._transformYawPitch.clone();
  78670. this._transformYawPitch.invert();
  78671. }
  78672. }
  78673. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78674. this.upAxisSpace = BABYLON.Space.LOCAL;
  78675. }
  78676. }
  78677. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78678. /**
  78679. * Gets or sets the minimum yaw angle that the bone can look to
  78680. */
  78681. get: function () {
  78682. return this._minYaw;
  78683. },
  78684. set: function (value) {
  78685. this._minYaw = value;
  78686. this._minYawSin = Math.sin(value);
  78687. this._minYawCos = Math.cos(value);
  78688. if (this._maxYaw != null) {
  78689. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78690. this._yawRange = this._maxYaw - this._minYaw;
  78691. }
  78692. },
  78693. enumerable: true,
  78694. configurable: true
  78695. });
  78696. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78697. /**
  78698. * Gets or sets the maximum yaw angle that the bone can look to
  78699. */
  78700. get: function () {
  78701. return this._maxYaw;
  78702. },
  78703. set: function (value) {
  78704. this._maxYaw = value;
  78705. this._maxYawSin = Math.sin(value);
  78706. this._maxYawCos = Math.cos(value);
  78707. if (this._minYaw != null) {
  78708. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78709. this._yawRange = this._maxYaw - this._minYaw;
  78710. }
  78711. },
  78712. enumerable: true,
  78713. configurable: true
  78714. });
  78715. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78716. /**
  78717. * Gets or sets the minimum pitch angle that the bone can look to
  78718. */
  78719. get: function () {
  78720. return this._minPitch;
  78721. },
  78722. set: function (value) {
  78723. this._minPitch = value;
  78724. this._minPitchTan = Math.tan(value);
  78725. },
  78726. enumerable: true,
  78727. configurable: true
  78728. });
  78729. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78730. /**
  78731. * Gets or sets the maximum pitch angle that the bone can look to
  78732. */
  78733. get: function () {
  78734. return this._maxPitch;
  78735. },
  78736. set: function (value) {
  78737. this._maxPitch = value;
  78738. this._maxPitchTan = Math.tan(value);
  78739. },
  78740. enumerable: true,
  78741. configurable: true
  78742. });
  78743. /**
  78744. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78745. */
  78746. BoneLookController.prototype.update = function () {
  78747. //skip the first frame when slerping so that the mesh rotation is correct
  78748. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78749. this._firstFrameSkipped = true;
  78750. return;
  78751. }
  78752. var bone = this.bone;
  78753. var bonePos = BoneLookController._tmpVecs[0];
  78754. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78755. var target = this.target;
  78756. var _tmpMat1 = BoneLookController._tmpMats[0];
  78757. var _tmpMat2 = BoneLookController._tmpMats[1];
  78758. var mesh = this.mesh;
  78759. var parentBone = bone.getParent();
  78760. var upAxis = BoneLookController._tmpVecs[1];
  78761. upAxis.copyFrom(this.upAxis);
  78762. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78763. if (this._transformYawPitch) {
  78764. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78765. }
  78766. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78767. }
  78768. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78769. mesh.getDirectionToRef(upAxis, upAxis);
  78770. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78771. upAxis.normalize();
  78772. }
  78773. }
  78774. var checkYaw = false;
  78775. var checkPitch = false;
  78776. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78777. checkYaw = true;
  78778. }
  78779. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78780. checkPitch = true;
  78781. }
  78782. if (checkYaw || checkPitch) {
  78783. var spaceMat = BoneLookController._tmpMats[2];
  78784. var spaceMatInv = BoneLookController._tmpMats[3];
  78785. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78786. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78787. }
  78788. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78789. spaceMat.copyFrom(mesh.getWorldMatrix());
  78790. }
  78791. else {
  78792. var forwardAxis = BoneLookController._tmpVecs[2];
  78793. forwardAxis.copyFrom(this._fowardAxis);
  78794. if (this._transformYawPitch) {
  78795. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78796. }
  78797. if (parentBone) {
  78798. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78799. }
  78800. else {
  78801. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78802. }
  78803. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78804. rightAxis.normalize();
  78805. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78806. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78807. }
  78808. spaceMat.invertToRef(spaceMatInv);
  78809. var xzlen = null;
  78810. if (checkPitch) {
  78811. var localTarget = BoneLookController._tmpVecs[3];
  78812. target.subtractToRef(bonePos, localTarget);
  78813. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78814. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78815. var pitch = Math.atan2(localTarget.y, xzlen);
  78816. var newPitch = pitch;
  78817. if (pitch > this._maxPitch) {
  78818. localTarget.y = this._maxPitchTan * xzlen;
  78819. newPitch = this._maxPitch;
  78820. }
  78821. else if (pitch < this._minPitch) {
  78822. localTarget.y = this._minPitchTan * xzlen;
  78823. newPitch = this._minPitch;
  78824. }
  78825. if (pitch != newPitch) {
  78826. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78827. localTarget.addInPlace(bonePos);
  78828. target = localTarget;
  78829. }
  78830. }
  78831. if (checkYaw) {
  78832. var localTarget = BoneLookController._tmpVecs[4];
  78833. target.subtractToRef(bonePos, localTarget);
  78834. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78835. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78836. var newYaw = yaw;
  78837. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78838. if (xzlen == null) {
  78839. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78840. }
  78841. if (this._yawRange > Math.PI) {
  78842. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78843. localTarget.z = this._maxYawCos * xzlen;
  78844. localTarget.x = this._maxYawSin * xzlen;
  78845. newYaw = this._maxYaw;
  78846. }
  78847. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78848. localTarget.z = this._minYawCos * xzlen;
  78849. localTarget.x = this._minYawSin * xzlen;
  78850. newYaw = this._minYaw;
  78851. }
  78852. }
  78853. else {
  78854. if (yaw > this._maxYaw) {
  78855. localTarget.z = this._maxYawCos * xzlen;
  78856. localTarget.x = this._maxYawSin * xzlen;
  78857. newYaw = this._maxYaw;
  78858. }
  78859. else if (yaw < this._minYaw) {
  78860. localTarget.z = this._minYawCos * xzlen;
  78861. localTarget.x = this._minYawSin * xzlen;
  78862. newYaw = this._minYaw;
  78863. }
  78864. }
  78865. }
  78866. if (this._slerping && this._yawRange > Math.PI) {
  78867. //are we going to be crossing into the min/max region?
  78868. var boneFwd = BoneLookController._tmpVecs[8];
  78869. boneFwd.copyFrom(BABYLON.Axis.Z);
  78870. if (this._transformYawPitch) {
  78871. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78872. }
  78873. var boneRotMat = BoneLookController._tmpMats[4];
  78874. this._boneQuat.toRotationMatrix(boneRotMat);
  78875. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78876. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78877. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78878. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78879. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78880. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78881. if (angBtwTar > angBtwMidYaw) {
  78882. if (xzlen == null) {
  78883. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78884. }
  78885. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78886. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78887. if (angBtwMin < angBtwMax) {
  78888. newYaw = boneYaw + Math.PI * .75;
  78889. localTarget.z = Math.cos(newYaw) * xzlen;
  78890. localTarget.x = Math.sin(newYaw) * xzlen;
  78891. }
  78892. else {
  78893. newYaw = boneYaw - Math.PI * .75;
  78894. localTarget.z = Math.cos(newYaw) * xzlen;
  78895. localTarget.x = Math.sin(newYaw) * xzlen;
  78896. }
  78897. }
  78898. }
  78899. if (yaw != newYaw) {
  78900. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78901. localTarget.addInPlace(bonePos);
  78902. target = localTarget;
  78903. }
  78904. }
  78905. }
  78906. var zaxis = BoneLookController._tmpVecs[5];
  78907. var xaxis = BoneLookController._tmpVecs[6];
  78908. var yaxis = BoneLookController._tmpVecs[7];
  78909. var _tmpQuat = BoneLookController._tmpQuat;
  78910. target.subtractToRef(bonePos, zaxis);
  78911. zaxis.normalize();
  78912. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78913. xaxis.normalize();
  78914. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78915. yaxis.normalize();
  78916. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78917. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78918. return;
  78919. }
  78920. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78921. return;
  78922. }
  78923. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78924. return;
  78925. }
  78926. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78927. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78928. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78929. }
  78930. if (this.slerpAmount < 1) {
  78931. if (!this._slerping) {
  78932. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78933. }
  78934. if (this._transformYawPitch) {
  78935. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78936. }
  78937. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78938. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78939. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78940. this._slerping = true;
  78941. }
  78942. else {
  78943. if (this._transformYawPitch) {
  78944. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78945. }
  78946. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78947. this._slerping = false;
  78948. }
  78949. };
  78950. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78951. var angDiff = ang2 - ang1;
  78952. angDiff %= Math.PI * 2;
  78953. if (angDiff > Math.PI) {
  78954. angDiff -= Math.PI * 2;
  78955. }
  78956. else if (angDiff < -Math.PI) {
  78957. angDiff += Math.PI * 2;
  78958. }
  78959. return angDiff;
  78960. };
  78961. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78962. ang1 %= (2 * Math.PI);
  78963. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78964. ang2 %= (2 * Math.PI);
  78965. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78966. var ab = 0;
  78967. if (ang1 < ang2) {
  78968. ab = ang2 - ang1;
  78969. }
  78970. else {
  78971. ab = ang1 - ang2;
  78972. }
  78973. if (ab > Math.PI) {
  78974. ab = Math.PI * 2 - ab;
  78975. }
  78976. return ab;
  78977. };
  78978. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78979. ang %= (2 * Math.PI);
  78980. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78981. ang1 %= (2 * Math.PI);
  78982. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78983. ang2 %= (2 * Math.PI);
  78984. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78985. if (ang1 < ang2) {
  78986. if (ang > ang1 && ang < ang2) {
  78987. return true;
  78988. }
  78989. }
  78990. else {
  78991. if (ang > ang2 && ang < ang1) {
  78992. return true;
  78993. }
  78994. }
  78995. return false;
  78996. };
  78997. 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()];
  78998. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78999. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79000. return BoneLookController;
  79001. }());
  79002. BABYLON.BoneLookController = BoneLookController;
  79003. })(BABYLON || (BABYLON = {}));
  79004. //# sourceMappingURL=babylon.boneLookController.js.map
  79005. var BABYLON;
  79006. (function (BABYLON) {
  79007. /**
  79008. * Class used to handle skinning animations
  79009. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79010. */
  79011. var Skeleton = /** @class */ (function () {
  79012. /**
  79013. * Creates a new skeleton
  79014. * @param name defines the skeleton name
  79015. * @param id defines the skeleton Id
  79016. * @param scene defines the hosting scene
  79017. */
  79018. function Skeleton(
  79019. /** defines the skeleton name */
  79020. name,
  79021. /** defines the skeleton Id */
  79022. id, scene) {
  79023. this.name = name;
  79024. this.id = id;
  79025. /**
  79026. * Gets the list of child bones
  79027. */
  79028. this.bones = new Array();
  79029. /**
  79030. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79031. */
  79032. this.needInitialSkinMatrix = false;
  79033. this._isDirty = true;
  79034. this._meshesWithPoseMatrix = new Array();
  79035. this._identity = BABYLON.Matrix.Identity();
  79036. this._ranges = {};
  79037. this._lastAbsoluteTransformsUpdateId = -1;
  79038. /**
  79039. * Specifies if the skeleton should be serialized
  79040. */
  79041. this.doNotSerialize = false;
  79042. this._animationPropertiesOverride = null;
  79043. // Events
  79044. /**
  79045. * An observable triggered before computing the skeleton's matrices
  79046. */
  79047. this.onBeforeComputeObservable = new BABYLON.Observable();
  79048. this.bones = [];
  79049. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79050. scene.skeletons.push(this);
  79051. //make sure it will recalculate the matrix next time prepare is called.
  79052. this._isDirty = true;
  79053. }
  79054. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79055. /**
  79056. * Gets or sets the animation properties override
  79057. */
  79058. get: function () {
  79059. if (!this._animationPropertiesOverride) {
  79060. return this._scene.animationPropertiesOverride;
  79061. }
  79062. return this._animationPropertiesOverride;
  79063. },
  79064. set: function (value) {
  79065. this._animationPropertiesOverride = value;
  79066. },
  79067. enumerable: true,
  79068. configurable: true
  79069. });
  79070. // Members
  79071. /**
  79072. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79073. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79074. * @returns a Float32Array containing matrices data
  79075. */
  79076. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79077. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79078. return mesh._bonesTransformMatrices;
  79079. }
  79080. if (!this._transformMatrices) {
  79081. this.prepare();
  79082. }
  79083. return this._transformMatrices;
  79084. };
  79085. /**
  79086. * Gets the current hosting scene
  79087. * @returns a scene object
  79088. */
  79089. Skeleton.prototype.getScene = function () {
  79090. return this._scene;
  79091. };
  79092. // Methods
  79093. /**
  79094. * Gets a string representing the current skeleton data
  79095. * @param fullDetails defines a boolean indicating if we want a verbose version
  79096. * @returns a string representing the current skeleton data
  79097. */
  79098. Skeleton.prototype.toString = function (fullDetails) {
  79099. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79100. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79101. if (fullDetails) {
  79102. ret += ", Ranges: {";
  79103. var first = true;
  79104. for (var name_1 in this._ranges) {
  79105. if (first) {
  79106. ret += ", ";
  79107. first = false;
  79108. }
  79109. ret += name_1;
  79110. }
  79111. ret += "}";
  79112. }
  79113. return ret;
  79114. };
  79115. /**
  79116. * Get bone's index searching by name
  79117. * @param name defines bone's name to search for
  79118. * @return the indice of the bone. Returns -1 if not found
  79119. */
  79120. Skeleton.prototype.getBoneIndexByName = function (name) {
  79121. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79122. if (this.bones[boneIndex].name === name) {
  79123. return boneIndex;
  79124. }
  79125. }
  79126. return -1;
  79127. };
  79128. /**
  79129. * Creater a new animation range
  79130. * @param name defines the name of the range
  79131. * @param from defines the start key
  79132. * @param to defines the end key
  79133. */
  79134. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79135. // check name not already in use
  79136. if (!this._ranges[name]) {
  79137. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79138. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79139. if (this.bones[i].animations[0]) {
  79140. this.bones[i].animations[0].createRange(name, from, to);
  79141. }
  79142. }
  79143. }
  79144. };
  79145. /**
  79146. * Delete a specific animation range
  79147. * @param name defines the name of the range
  79148. * @param deleteFrames defines if frames must be removed as well
  79149. */
  79150. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79151. if (deleteFrames === void 0) { deleteFrames = true; }
  79152. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79153. if (this.bones[i].animations[0]) {
  79154. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79155. }
  79156. }
  79157. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79158. };
  79159. /**
  79160. * Gets a specific animation range
  79161. * @param name defines the name of the range to look for
  79162. * @returns the requested animation range or null if not found
  79163. */
  79164. Skeleton.prototype.getAnimationRange = function (name) {
  79165. return this._ranges[name];
  79166. };
  79167. /**
  79168. * Gets the list of all animation ranges defined on this skeleton
  79169. * @returns an array
  79170. */
  79171. Skeleton.prototype.getAnimationRanges = function () {
  79172. var animationRanges = [];
  79173. var name;
  79174. var i = 0;
  79175. for (name in this._ranges) {
  79176. animationRanges[i] = this._ranges[name];
  79177. i++;
  79178. }
  79179. return animationRanges;
  79180. };
  79181. /**
  79182. * Copy animation range from a source skeleton.
  79183. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79184. * @param source defines the source skeleton
  79185. * @param name defines the name of the range to copy
  79186. * @param rescaleAsRequired defines if rescaling must be applied if required
  79187. * @returns true if operation was successful
  79188. */
  79189. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79190. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79191. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79192. return false;
  79193. }
  79194. var ret = true;
  79195. var frameOffset = this._getHighestAnimationFrame() + 1;
  79196. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79197. var boneDict = {};
  79198. var sourceBones = source.bones;
  79199. var nBones;
  79200. var i;
  79201. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79202. boneDict[sourceBones[i].name] = sourceBones[i];
  79203. }
  79204. if (this.bones.length !== sourceBones.length) {
  79205. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79206. ret = false;
  79207. }
  79208. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79209. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79210. var boneName = this.bones[i].name;
  79211. var sourceBone = boneDict[boneName];
  79212. if (sourceBone) {
  79213. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79214. }
  79215. else {
  79216. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79217. ret = false;
  79218. }
  79219. }
  79220. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79221. var range = source.getAnimationRange(name);
  79222. if (range) {
  79223. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79224. }
  79225. return ret;
  79226. };
  79227. /**
  79228. * Forces the skeleton to go to rest pose
  79229. */
  79230. Skeleton.prototype.returnToRest = function () {
  79231. for (var index = 0; index < this.bones.length; index++) {
  79232. this.bones[index].returnToRest();
  79233. }
  79234. };
  79235. Skeleton.prototype._getHighestAnimationFrame = function () {
  79236. var ret = 0;
  79237. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79238. if (this.bones[i].animations[0]) {
  79239. var highest = this.bones[i].animations[0].getHighestFrame();
  79240. if (ret < highest) {
  79241. ret = highest;
  79242. }
  79243. }
  79244. }
  79245. return ret;
  79246. };
  79247. /**
  79248. * Begin a specific animation range
  79249. * @param name defines the name of the range to start
  79250. * @param loop defines if looping must be turned on (false by default)
  79251. * @param speedRatio defines the speed ratio to apply (1 by default)
  79252. * @param onAnimationEnd defines a callback which will be called when animation will end
  79253. * @returns a new animatable
  79254. */
  79255. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79256. var range = this.getAnimationRange(name);
  79257. if (!range) {
  79258. return null;
  79259. }
  79260. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79261. };
  79262. /** @hidden */
  79263. Skeleton.prototype._markAsDirty = function () {
  79264. this._isDirty = true;
  79265. };
  79266. /** @hidden */
  79267. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79268. this._meshesWithPoseMatrix.push(mesh);
  79269. };
  79270. /** @hidden */
  79271. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79272. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79273. if (index > -1) {
  79274. this._meshesWithPoseMatrix.splice(index, 1);
  79275. }
  79276. };
  79277. /** @hidden */
  79278. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79279. this.onBeforeComputeObservable.notifyObservers(this);
  79280. for (var index = 0; index < this.bones.length; index++) {
  79281. var bone = this.bones[index];
  79282. var parentBone = bone.getParent();
  79283. if (parentBone) {
  79284. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79285. }
  79286. else {
  79287. if (initialSkinMatrix) {
  79288. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79289. }
  79290. else {
  79291. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79292. }
  79293. }
  79294. if (bone._index !== -1) {
  79295. var mappedIndex = bone._index === null ? index : bone._index;
  79296. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79297. }
  79298. }
  79299. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79300. };
  79301. /**
  79302. * Build all resources required to render a skeleton
  79303. */
  79304. Skeleton.prototype.prepare = function () {
  79305. if (!this._isDirty) {
  79306. return;
  79307. }
  79308. if (this.needInitialSkinMatrix) {
  79309. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79310. var mesh = this._meshesWithPoseMatrix[index];
  79311. var poseMatrix = mesh.getPoseMatrix();
  79312. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79313. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79314. }
  79315. if (this._synchronizedWithMesh !== mesh) {
  79316. this._synchronizedWithMesh = mesh;
  79317. // Prepare bones
  79318. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79319. var bone = this.bones[boneIndex];
  79320. if (!bone.getParent()) {
  79321. var matrix = bone.getBaseMatrix();
  79322. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79323. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79324. }
  79325. }
  79326. }
  79327. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79328. }
  79329. }
  79330. else {
  79331. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79332. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79333. }
  79334. this._computeTransformMatrices(this._transformMatrices, null);
  79335. }
  79336. this._isDirty = false;
  79337. this._scene._activeBones.addCount(this.bones.length, false);
  79338. };
  79339. /**
  79340. * Gets the list of animatables currently running for this skeleton
  79341. * @returns an array of animatables
  79342. */
  79343. Skeleton.prototype.getAnimatables = function () {
  79344. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79345. this._animatables = [];
  79346. for (var index = 0; index < this.bones.length; index++) {
  79347. this._animatables.push(this.bones[index]);
  79348. }
  79349. }
  79350. return this._animatables;
  79351. };
  79352. /**
  79353. * Clone the current skeleton
  79354. * @param name defines the name of the new skeleton
  79355. * @param id defines the id of the enw skeleton
  79356. * @returns the new skeleton
  79357. */
  79358. Skeleton.prototype.clone = function (name, id) {
  79359. var result = new Skeleton(name, id || name, this._scene);
  79360. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79361. for (var index = 0; index < this.bones.length; index++) {
  79362. var source = this.bones[index];
  79363. var parentBone = null;
  79364. var parent_1 = source.getParent();
  79365. if (parent_1) {
  79366. var parentIndex = this.bones.indexOf(parent_1);
  79367. parentBone = result.bones[parentIndex];
  79368. }
  79369. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79370. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79371. }
  79372. if (this._ranges) {
  79373. result._ranges = {};
  79374. for (var rangeName in this._ranges) {
  79375. var range = this._ranges[rangeName];
  79376. if (range) {
  79377. result._ranges[rangeName] = range.clone();
  79378. }
  79379. }
  79380. }
  79381. this._isDirty = true;
  79382. return result;
  79383. };
  79384. /**
  79385. * Enable animation blending for this skeleton
  79386. * @param blendingSpeed defines the blending speed to apply
  79387. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79388. */
  79389. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79390. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79391. this.bones.forEach(function (bone) {
  79392. bone.animations.forEach(function (animation) {
  79393. animation.enableBlending = true;
  79394. animation.blendingSpeed = blendingSpeed;
  79395. });
  79396. });
  79397. };
  79398. /**
  79399. * Releases all resources associated with the current skeleton
  79400. */
  79401. Skeleton.prototype.dispose = function () {
  79402. this._meshesWithPoseMatrix = [];
  79403. // Animations
  79404. this.getScene().stopAnimation(this);
  79405. // Remove from scene
  79406. this.getScene().removeSkeleton(this);
  79407. };
  79408. /**
  79409. * Serialize the skeleton in a JSON object
  79410. * @returns a JSON object
  79411. */
  79412. Skeleton.prototype.serialize = function () {
  79413. var serializationObject = {};
  79414. serializationObject.name = this.name;
  79415. serializationObject.id = this.id;
  79416. if (this.dimensionsAtRest) {
  79417. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79418. }
  79419. serializationObject.bones = [];
  79420. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79421. for (var index = 0; index < this.bones.length; index++) {
  79422. var bone = this.bones[index];
  79423. var parent_2 = bone.getParent();
  79424. var serializedBone = {
  79425. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79426. name: bone.name,
  79427. matrix: bone.getBaseMatrix().toArray(),
  79428. rest: bone.getRestPose().toArray()
  79429. };
  79430. serializationObject.bones.push(serializedBone);
  79431. if (bone.length) {
  79432. serializedBone.length = bone.length;
  79433. }
  79434. if (bone.metadata) {
  79435. serializedBone.metadata = bone.metadata;
  79436. }
  79437. if (bone.animations && bone.animations.length > 0) {
  79438. serializedBone.animation = bone.animations[0].serialize();
  79439. }
  79440. serializationObject.ranges = [];
  79441. for (var name in this._ranges) {
  79442. var source = this._ranges[name];
  79443. if (!source) {
  79444. continue;
  79445. }
  79446. var range = {};
  79447. range.name = name;
  79448. range.from = source.from;
  79449. range.to = source.to;
  79450. serializationObject.ranges.push(range);
  79451. }
  79452. }
  79453. return serializationObject;
  79454. };
  79455. /**
  79456. * Creates a new skeleton from serialized data
  79457. * @param parsedSkeleton defines the serialized data
  79458. * @param scene defines the hosting scene
  79459. * @returns a new skeleton
  79460. */
  79461. Skeleton.Parse = function (parsedSkeleton, scene) {
  79462. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79463. if (parsedSkeleton.dimensionsAtRest) {
  79464. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79465. }
  79466. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79467. var index;
  79468. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79469. var parsedBone = parsedSkeleton.bones[index];
  79470. var parentBone = null;
  79471. if (parsedBone.parentBoneIndex > -1) {
  79472. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79473. }
  79474. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79475. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79476. if (parsedBone.length) {
  79477. bone.length = parsedBone.length;
  79478. }
  79479. if (parsedBone.metadata) {
  79480. bone.metadata = parsedBone.metadata;
  79481. }
  79482. if (parsedBone.animation) {
  79483. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79484. }
  79485. }
  79486. // placed after bones, so createAnimationRange can cascade down
  79487. if (parsedSkeleton.ranges) {
  79488. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79489. var data = parsedSkeleton.ranges[index];
  79490. skeleton.createAnimationRange(data.name, data.from, data.to);
  79491. }
  79492. }
  79493. return skeleton;
  79494. };
  79495. /**
  79496. * Compute all node absolute transforms
  79497. * @param forceUpdate defines if computation must be done even if cache is up to date
  79498. */
  79499. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79500. if (forceUpdate === void 0) { forceUpdate = false; }
  79501. var renderId = this._scene.getRenderId();
  79502. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79503. this.bones[0].computeAbsoluteTransforms();
  79504. this._lastAbsoluteTransformsUpdateId = renderId;
  79505. }
  79506. };
  79507. /**
  79508. * Gets the root pose matrix
  79509. * @returns a matrix
  79510. */
  79511. Skeleton.prototype.getPoseMatrix = function () {
  79512. var poseMatrix = null;
  79513. if (this._meshesWithPoseMatrix.length > 0) {
  79514. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79515. }
  79516. return poseMatrix;
  79517. };
  79518. /**
  79519. * Sorts bones per internal index
  79520. */
  79521. Skeleton.prototype.sortBones = function () {
  79522. var bones = new Array();
  79523. var visited = new Array(this.bones.length);
  79524. for (var index = 0; index < this.bones.length; index++) {
  79525. this._sortBones(index, bones, visited);
  79526. }
  79527. this.bones = bones;
  79528. };
  79529. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79530. if (visited[index]) {
  79531. return;
  79532. }
  79533. visited[index] = true;
  79534. var bone = this.bones[index];
  79535. if (bone._index === undefined) {
  79536. bone._index = index;
  79537. }
  79538. var parentBone = bone.getParent();
  79539. if (parentBone) {
  79540. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79541. }
  79542. bones.push(bone);
  79543. };
  79544. return Skeleton;
  79545. }());
  79546. BABYLON.Skeleton = Skeleton;
  79547. })(BABYLON || (BABYLON = {}));
  79548. //# sourceMappingURL=babylon.skeleton.js.map
  79549. var BABYLON;
  79550. (function (BABYLON) {
  79551. var SphericalPolynomial = /** @class */ (function () {
  79552. function SphericalPolynomial() {
  79553. this.x = BABYLON.Vector3.Zero();
  79554. this.y = BABYLON.Vector3.Zero();
  79555. this.z = BABYLON.Vector3.Zero();
  79556. this.xx = BABYLON.Vector3.Zero();
  79557. this.yy = BABYLON.Vector3.Zero();
  79558. this.zz = BABYLON.Vector3.Zero();
  79559. this.xy = BABYLON.Vector3.Zero();
  79560. this.yz = BABYLON.Vector3.Zero();
  79561. this.zx = BABYLON.Vector3.Zero();
  79562. }
  79563. SphericalPolynomial.prototype.addAmbient = function (color) {
  79564. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79565. this.xx = this.xx.add(colorVector);
  79566. this.yy = this.yy.add(colorVector);
  79567. this.zz = this.zz.add(colorVector);
  79568. };
  79569. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79570. var result = new SphericalPolynomial();
  79571. result.x = harmonics.L11.scale(1.02333);
  79572. result.y = harmonics.L1_1.scale(1.02333);
  79573. result.z = harmonics.L10.scale(1.02333);
  79574. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79575. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79576. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79577. result.yz = harmonics.L2_1.scale(0.858086);
  79578. result.zx = harmonics.L21.scale(0.858086);
  79579. result.xy = harmonics.L2_2.scale(0.858086);
  79580. result.scale(1.0 / Math.PI);
  79581. return result;
  79582. };
  79583. SphericalPolynomial.prototype.scale = function (scale) {
  79584. this.x = this.x.scale(scale);
  79585. this.y = this.y.scale(scale);
  79586. this.z = this.z.scale(scale);
  79587. this.xx = this.xx.scale(scale);
  79588. this.yy = this.yy.scale(scale);
  79589. this.zz = this.zz.scale(scale);
  79590. this.yz = this.yz.scale(scale);
  79591. this.zx = this.zx.scale(scale);
  79592. this.xy = this.xy.scale(scale);
  79593. };
  79594. return SphericalPolynomial;
  79595. }());
  79596. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79597. var SphericalHarmonics = /** @class */ (function () {
  79598. function SphericalHarmonics() {
  79599. this.L00 = BABYLON.Vector3.Zero();
  79600. this.L1_1 = BABYLON.Vector3.Zero();
  79601. this.L10 = BABYLON.Vector3.Zero();
  79602. this.L11 = BABYLON.Vector3.Zero();
  79603. this.L2_2 = BABYLON.Vector3.Zero();
  79604. this.L2_1 = BABYLON.Vector3.Zero();
  79605. this.L20 = BABYLON.Vector3.Zero();
  79606. this.L21 = BABYLON.Vector3.Zero();
  79607. this.L22 = BABYLON.Vector3.Zero();
  79608. }
  79609. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79610. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79611. var c = colorVector.scale(deltaSolidAngle);
  79612. this.L00 = this.L00.add(c.scale(0.282095));
  79613. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79614. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79615. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79616. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79617. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79618. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79619. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79620. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79621. };
  79622. SphericalHarmonics.prototype.scale = function (scale) {
  79623. this.L00 = this.L00.scale(scale);
  79624. this.L1_1 = this.L1_1.scale(scale);
  79625. this.L10 = this.L10.scale(scale);
  79626. this.L11 = this.L11.scale(scale);
  79627. this.L2_2 = this.L2_2.scale(scale);
  79628. this.L2_1 = this.L2_1.scale(scale);
  79629. this.L20 = this.L20.scale(scale);
  79630. this.L21 = this.L21.scale(scale);
  79631. this.L22 = this.L22.scale(scale);
  79632. };
  79633. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79634. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79635. //
  79636. // E_lm = A_l * L_lm
  79637. //
  79638. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79639. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79640. // the scaling factors are given in equation 9.
  79641. // Constant (Band 0)
  79642. this.L00 = this.L00.scale(3.141593);
  79643. // Linear (Band 1)
  79644. this.L1_1 = this.L1_1.scale(2.094395);
  79645. this.L10 = this.L10.scale(2.094395);
  79646. this.L11 = this.L11.scale(2.094395);
  79647. // Quadratic (Band 2)
  79648. this.L2_2 = this.L2_2.scale(0.785398);
  79649. this.L2_1 = this.L2_1.scale(0.785398);
  79650. this.L20 = this.L20.scale(0.785398);
  79651. this.L21 = this.L21.scale(0.785398);
  79652. this.L22 = this.L22.scale(0.785398);
  79653. };
  79654. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79655. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79656. // L = (1/pi) * E * rho
  79657. //
  79658. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79659. this.scale(1.0 / Math.PI);
  79660. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79661. // (The pixel shader must apply albedo after texture fetches, etc).
  79662. };
  79663. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79664. var result = new SphericalHarmonics();
  79665. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79666. result.L1_1 = polynomial.y.scale(0.977204);
  79667. result.L10 = polynomial.z.scale(0.977204);
  79668. result.L11 = polynomial.x.scale(0.977204);
  79669. result.L2_2 = polynomial.xy.scale(1.16538);
  79670. result.L2_1 = polynomial.yz.scale(1.16538);
  79671. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79672. result.L21 = polynomial.zx.scale(1.16538);
  79673. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79674. result.scale(Math.PI);
  79675. return result;
  79676. };
  79677. return SphericalHarmonics;
  79678. }());
  79679. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79680. })(BABYLON || (BABYLON = {}));
  79681. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79682. var BABYLON;
  79683. (function (BABYLON) {
  79684. var FileFaceOrientation = /** @class */ (function () {
  79685. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79686. this.name = name;
  79687. this.worldAxisForNormal = worldAxisForNormal;
  79688. this.worldAxisForFileX = worldAxisForFileX;
  79689. this.worldAxisForFileY = worldAxisForFileY;
  79690. }
  79691. return FileFaceOrientation;
  79692. }());
  79693. ;
  79694. /**
  79695. * Helper class dealing with the extraction of spherical polynomial dataArray
  79696. * from a cube map.
  79697. */
  79698. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79699. function CubeMapToSphericalPolynomialTools() {
  79700. }
  79701. /**
  79702. * Converts a texture to the according Spherical Polynomial data.
  79703. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79704. *
  79705. * @param texture The texture to extract the information from.
  79706. * @return The Spherical Polynomial data.
  79707. */
  79708. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79709. if (!texture.isCube) {
  79710. // Only supports cube Textures currently.
  79711. return null;
  79712. }
  79713. var size = texture.getSize().width;
  79714. var right = texture.readPixels(0);
  79715. var left = texture.readPixels(1);
  79716. var up;
  79717. var down;
  79718. if (texture.isRenderTarget) {
  79719. up = texture.readPixels(3);
  79720. down = texture.readPixels(2);
  79721. }
  79722. else {
  79723. up = texture.readPixels(2);
  79724. down = texture.readPixels(3);
  79725. }
  79726. var front = texture.readPixels(4);
  79727. var back = texture.readPixels(5);
  79728. var gammaSpace = texture.gammaSpace;
  79729. // Always read as RGBA.
  79730. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79731. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79732. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79733. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79734. }
  79735. var cubeInfo = {
  79736. size: size,
  79737. right: right,
  79738. left: left,
  79739. up: up,
  79740. down: down,
  79741. front: front,
  79742. back: back,
  79743. format: format,
  79744. type: type,
  79745. gammaSpace: gammaSpace,
  79746. };
  79747. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79748. };
  79749. /**
  79750. * Converts a cubemap to the according Spherical Polynomial data.
  79751. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79752. *
  79753. * @param cubeInfo The Cube map to extract the information from.
  79754. * @return The Spherical Polynomial data.
  79755. */
  79756. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79757. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79758. var totalSolidAngle = 0.0;
  79759. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79760. var du = 2.0 / cubeInfo.size;
  79761. var dv = du;
  79762. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79763. var minUV = du * 0.5 - 1.0;
  79764. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79765. var fileFace = this.FileFaces[faceIndex];
  79766. var dataArray = cubeInfo[fileFace.name];
  79767. var v = minUV;
  79768. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79769. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79770. // Because SP is still linear, so summation is fine in that basis.
  79771. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79772. for (var y = 0; y < cubeInfo.size; y++) {
  79773. var u = minUV;
  79774. for (var x = 0; x < cubeInfo.size; x++) {
  79775. // World direction (not normalised)
  79776. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79777. worldDirection.normalize();
  79778. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79779. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79780. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79781. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79782. // Handle Integer types.
  79783. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79784. r /= 255;
  79785. g /= 255;
  79786. b /= 255;
  79787. }
  79788. // Handle Gamma space textures.
  79789. if (cubeInfo.gammaSpace) {
  79790. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79791. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79792. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79793. }
  79794. var color = new BABYLON.Color3(r, g, b);
  79795. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79796. totalSolidAngle += deltaSolidAngle;
  79797. u += du;
  79798. }
  79799. v += dv;
  79800. }
  79801. }
  79802. // Solid angle for entire sphere is 4*pi
  79803. var sphereSolidAngle = 4.0 * Math.PI;
  79804. // Adjust the solid angle to allow for how many faces we processed.
  79805. var facesProcessed = 6.0;
  79806. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79807. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79808. // This is needed because the numerical integration over the cube uses a
  79809. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79810. // and also to compensate for accumulative error due to float precision in the summation.
  79811. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79812. sphericalHarmonics.scale(correctionFactor);
  79813. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79814. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79815. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79816. };
  79817. CubeMapToSphericalPolynomialTools.FileFaces = [
  79818. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79819. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79820. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79821. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79822. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79823. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79824. ];
  79825. return CubeMapToSphericalPolynomialTools;
  79826. }());
  79827. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79828. })(BABYLON || (BABYLON = {}));
  79829. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79830. var BABYLON;
  79831. (function (BABYLON) {
  79832. /**
  79833. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79834. */
  79835. var PanoramaToCubeMapTools = /** @class */ (function () {
  79836. function PanoramaToCubeMapTools() {
  79837. }
  79838. /**
  79839. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79840. *
  79841. * @param float32Array The source data.
  79842. * @param inputWidth The width of the input panorama.
  79843. * @param inputhHeight The height of the input panorama.
  79844. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79845. * @return The cubemap data
  79846. */
  79847. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79848. if (!float32Array) {
  79849. throw "ConvertPanoramaToCubemap: input cannot be null";
  79850. }
  79851. if (float32Array.length != inputWidth * inputHeight * 3) {
  79852. throw "ConvertPanoramaToCubemap: input size is wrong";
  79853. }
  79854. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79855. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79856. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79857. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79858. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79859. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79860. return {
  79861. front: textureFront,
  79862. back: textureBack,
  79863. left: textureLeft,
  79864. right: textureRight,
  79865. up: textureUp,
  79866. down: textureDown,
  79867. size: size,
  79868. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79869. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79870. gammaSpace: false,
  79871. };
  79872. };
  79873. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79874. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79875. var textureArray = new Float32Array(buffer);
  79876. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79877. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79878. var dy = 1 / texSize;
  79879. var fy = 0;
  79880. for (var y = 0; y < texSize; y++) {
  79881. var xv1 = faceData[0];
  79882. var xv2 = faceData[2];
  79883. for (var x = 0; x < texSize; x++) {
  79884. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79885. v.normalize();
  79886. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79887. // 3 channels per pixels
  79888. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79889. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79890. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79891. xv1 = xv1.add(rotDX1);
  79892. xv2 = xv2.add(rotDX2);
  79893. }
  79894. fy += dy;
  79895. }
  79896. return textureArray;
  79897. };
  79898. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79899. var theta = Math.atan2(vDir.z, vDir.x);
  79900. var phi = Math.acos(vDir.y);
  79901. while (theta < -Math.PI)
  79902. theta += 2 * Math.PI;
  79903. while (theta > Math.PI)
  79904. theta -= 2 * Math.PI;
  79905. var dx = theta / Math.PI;
  79906. var dy = phi / Math.PI;
  79907. // recenter.
  79908. dx = dx * 0.5 + 0.5;
  79909. var px = Math.round(dx * inputWidth);
  79910. if (px < 0)
  79911. px = 0;
  79912. else if (px >= inputWidth)
  79913. px = inputWidth - 1;
  79914. var py = Math.round(dy * inputHeight);
  79915. if (py < 0)
  79916. py = 0;
  79917. else if (py >= inputHeight)
  79918. py = inputHeight - 1;
  79919. var inputY = (inputHeight - py - 1);
  79920. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79921. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79922. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79923. return {
  79924. r: r,
  79925. g: g,
  79926. b: b
  79927. };
  79928. };
  79929. PanoramaToCubeMapTools.FACE_FRONT = [
  79930. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79931. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79932. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79933. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79934. ];
  79935. PanoramaToCubeMapTools.FACE_BACK = [
  79936. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79937. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79938. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79939. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79940. ];
  79941. PanoramaToCubeMapTools.FACE_RIGHT = [
  79942. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79943. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79944. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79945. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79946. ];
  79947. PanoramaToCubeMapTools.FACE_LEFT = [
  79948. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79949. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79950. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79951. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79952. ];
  79953. PanoramaToCubeMapTools.FACE_DOWN = [
  79954. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79955. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79956. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79957. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79958. ];
  79959. PanoramaToCubeMapTools.FACE_UP = [
  79960. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79961. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79962. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79963. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79964. ];
  79965. return PanoramaToCubeMapTools;
  79966. }());
  79967. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79968. })(BABYLON || (BABYLON = {}));
  79969. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79970. var BABYLON;
  79971. (function (BABYLON) {
  79972. ;
  79973. /**
  79974. * This groups tools to convert HDR texture to native colors array.
  79975. */
  79976. var HDRTools = /** @class */ (function () {
  79977. function HDRTools() {
  79978. }
  79979. HDRTools.Ldexp = function (mantissa, exponent) {
  79980. if (exponent > 1023) {
  79981. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79982. }
  79983. if (exponent < -1074) {
  79984. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79985. }
  79986. return mantissa * Math.pow(2, exponent);
  79987. };
  79988. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79989. if (exponent > 0) { /*nonzero pixel*/
  79990. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79991. float32array[index + 0] = red * exponent;
  79992. float32array[index + 1] = green * exponent;
  79993. float32array[index + 2] = blue * exponent;
  79994. }
  79995. else {
  79996. float32array[index + 0] = 0;
  79997. float32array[index + 1] = 0;
  79998. float32array[index + 2] = 0;
  79999. }
  80000. };
  80001. HDRTools.readStringLine = function (uint8array, startIndex) {
  80002. var line = "";
  80003. var character = "";
  80004. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80005. character = String.fromCharCode(uint8array[i]);
  80006. if (character == "\n") {
  80007. break;
  80008. }
  80009. line += character;
  80010. }
  80011. return line;
  80012. };
  80013. /**
  80014. * Reads header information from an RGBE texture stored in a native array.
  80015. * More information on this format are available here:
  80016. * https://en.wikipedia.org/wiki/RGBE_image_format
  80017. *
  80018. * @param uint8array The binary file stored in native array.
  80019. * @return The header information.
  80020. */
  80021. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80022. var height = 0;
  80023. var width = 0;
  80024. var line = this.readStringLine(uint8array, 0);
  80025. if (line[0] != '#' || line[1] != '?') {
  80026. throw "Bad HDR Format.";
  80027. }
  80028. var endOfHeader = false;
  80029. var findFormat = false;
  80030. var lineIndex = 0;
  80031. do {
  80032. lineIndex += (line.length + 1);
  80033. line = this.readStringLine(uint8array, lineIndex);
  80034. if (line == "FORMAT=32-bit_rle_rgbe") {
  80035. findFormat = true;
  80036. }
  80037. else if (line.length == 0) {
  80038. endOfHeader = true;
  80039. }
  80040. } while (!endOfHeader);
  80041. if (!findFormat) {
  80042. throw "HDR Bad header format, unsupported FORMAT";
  80043. }
  80044. lineIndex += (line.length + 1);
  80045. line = this.readStringLine(uint8array, lineIndex);
  80046. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80047. var match = sizeRegexp.exec(line);
  80048. // TODO. Support +Y and -X if needed.
  80049. if (!match || match.length < 3) {
  80050. throw "HDR Bad header format, no size";
  80051. }
  80052. width = parseInt(match[2]);
  80053. height = parseInt(match[1]);
  80054. if (width < 8 || width > 0x7fff) {
  80055. throw "HDR Bad header format, unsupported size";
  80056. }
  80057. lineIndex += (line.length + 1);
  80058. return {
  80059. height: height,
  80060. width: width,
  80061. dataPosition: lineIndex
  80062. };
  80063. };
  80064. /**
  80065. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80066. * This RGBE texture needs to store the information as a panorama.
  80067. *
  80068. * More information on this format are available here:
  80069. * https://en.wikipedia.org/wiki/RGBE_image_format
  80070. *
  80071. * @param buffer The binary file stored in an array buffer.
  80072. * @param size The expected size of the extracted cubemap.
  80073. * @return The Cube Map information.
  80074. */
  80075. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80076. var uint8array = new Uint8Array(buffer);
  80077. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80078. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80079. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80080. return cubeMapData;
  80081. };
  80082. /**
  80083. * Returns the pixels data extracted from an RGBE texture.
  80084. * This pixels will be stored left to right up to down in the R G B order in one array.
  80085. *
  80086. * More information on this format are available here:
  80087. * https://en.wikipedia.org/wiki/RGBE_image_format
  80088. *
  80089. * @param uint8array The binary file stored in an array buffer.
  80090. * @param hdrInfo The header information of the file.
  80091. * @return The pixels data in RGB right to left up to down order.
  80092. */
  80093. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80094. // Keep for multi format supports.
  80095. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80096. };
  80097. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80098. var num_scanlines = hdrInfo.height;
  80099. var scanline_width = hdrInfo.width;
  80100. var a, b, c, d, count;
  80101. var dataIndex = hdrInfo.dataPosition;
  80102. var index = 0, endIndex = 0, i = 0;
  80103. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80104. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80105. // 3 channels of 4 bytes per pixel in float.
  80106. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80107. var resultArray = new Float32Array(resultBuffer);
  80108. // read in each successive scanline
  80109. while (num_scanlines > 0) {
  80110. a = uint8array[dataIndex++];
  80111. b = uint8array[dataIndex++];
  80112. c = uint8array[dataIndex++];
  80113. d = uint8array[dataIndex++];
  80114. if (a != 2 || b != 2 || (c & 0x80)) {
  80115. // this file is not run length encoded
  80116. throw "HDR Bad header format, not RLE";
  80117. }
  80118. if (((c << 8) | d) != scanline_width) {
  80119. throw "HDR Bad header format, wrong scan line width";
  80120. }
  80121. index = 0;
  80122. // read each of the four channels for the scanline into the buffer
  80123. for (i = 0; i < 4; i++) {
  80124. endIndex = (i + 1) * scanline_width;
  80125. while (index < endIndex) {
  80126. a = uint8array[dataIndex++];
  80127. b = uint8array[dataIndex++];
  80128. if (a > 128) {
  80129. // a run of the same value
  80130. count = a - 128;
  80131. if ((count == 0) || (count > endIndex - index)) {
  80132. throw "HDR Bad Format, bad scanline data (run)";
  80133. }
  80134. while (count-- > 0) {
  80135. scanLineArray[index++] = b;
  80136. }
  80137. }
  80138. else {
  80139. // a non-run
  80140. count = a;
  80141. if ((count == 0) || (count > endIndex - index)) {
  80142. throw "HDR Bad Format, bad scanline data (non-run)";
  80143. }
  80144. scanLineArray[index++] = b;
  80145. if (--count > 0) {
  80146. for (var j = 0; j < count; j++) {
  80147. scanLineArray[index++] = uint8array[dataIndex++];
  80148. }
  80149. }
  80150. }
  80151. }
  80152. }
  80153. // now convert data from buffer into floats
  80154. for (i = 0; i < scanline_width; i++) {
  80155. a = scanLineArray[i];
  80156. b = scanLineArray[i + scanline_width];
  80157. c = scanLineArray[i + 2 * scanline_width];
  80158. d = scanLineArray[i + 3 * scanline_width];
  80159. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80160. }
  80161. num_scanlines--;
  80162. }
  80163. return resultArray;
  80164. };
  80165. return HDRTools;
  80166. }());
  80167. BABYLON.HDRTools = HDRTools;
  80168. })(BABYLON || (BABYLON = {}));
  80169. //# sourceMappingURL=babylon.hdr.js.map
  80170. var BABYLON;
  80171. (function (BABYLON) {
  80172. /**
  80173. * This represents a texture coming from an HDR input.
  80174. *
  80175. * The only supported format is currently panorama picture stored in RGBE format.
  80176. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80177. */
  80178. var HDRCubeTexture = /** @class */ (function (_super) {
  80179. __extends(HDRCubeTexture, _super);
  80180. /**
  80181. * Instantiates an HDRTexture from the following parameters.
  80182. *
  80183. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80184. * @param scene The scene the texture will be used in
  80185. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80186. * @param noMipmap Forces to not generate the mipmap if true
  80187. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80188. * @param gammaSpace 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)
  80189. * @param reserved Reserved flag for internal use.
  80190. */
  80191. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80192. if (noMipmap === void 0) { noMipmap = false; }
  80193. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80194. if (gammaSpace === void 0) { gammaSpace = false; }
  80195. if (reserved === void 0) { reserved = false; }
  80196. if (onLoad === void 0) { onLoad = null; }
  80197. if (onError === void 0) { onError = null; }
  80198. var _this = _super.call(this, scene) || this;
  80199. _this._generateHarmonics = true;
  80200. _this._onLoad = null;
  80201. _this._onError = null;
  80202. /**
  80203. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80204. */
  80205. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80206. _this._isBlocking = true;
  80207. _this._rotationY = 0;
  80208. /**
  80209. * Gets or sets the center of the bounding box associated with the cube texture
  80210. * It must define where the camera used to render the texture was set
  80211. */
  80212. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80213. if (!url) {
  80214. return _this;
  80215. }
  80216. _this.name = url;
  80217. _this.url = url;
  80218. _this.hasAlpha = false;
  80219. _this.isCube = true;
  80220. _this._textureMatrix = BABYLON.Matrix.Identity();
  80221. _this._onLoad = onLoad;
  80222. _this._onError = onError;
  80223. _this.gammaSpace = gammaSpace;
  80224. _this._noMipmap = noMipmap;
  80225. _this._size = size;
  80226. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80227. if (!_this._texture) {
  80228. if (!scene.useDelayedTextureLoading) {
  80229. _this.loadTexture();
  80230. }
  80231. else {
  80232. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80233. }
  80234. }
  80235. return _this;
  80236. }
  80237. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80238. /**
  80239. * Gets wether or not the texture is blocking during loading.
  80240. */
  80241. get: function () {
  80242. return this._isBlocking;
  80243. },
  80244. /**
  80245. * Sets wether or not the texture is blocking during loading.
  80246. */
  80247. set: function (value) {
  80248. this._isBlocking = value;
  80249. },
  80250. enumerable: true,
  80251. configurable: true
  80252. });
  80253. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80254. /**
  80255. * Gets texture matrix rotation angle around Y axis radians.
  80256. */
  80257. get: function () {
  80258. return this._rotationY;
  80259. },
  80260. /**
  80261. * Sets texture matrix rotation angle around Y axis in radians.
  80262. */
  80263. set: function (value) {
  80264. this._rotationY = value;
  80265. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80266. },
  80267. enumerable: true,
  80268. configurable: true
  80269. });
  80270. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80271. get: function () {
  80272. return this._boundingBoxSize;
  80273. },
  80274. /**
  80275. * Gets or sets the size of the bounding box associated with the cube texture
  80276. * When defined, the cubemap will switch to local mode
  80277. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80278. * @example https://www.babylonjs-playground.com/#RNASML
  80279. */
  80280. set: function (value) {
  80281. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80282. return;
  80283. }
  80284. this._boundingBoxSize = value;
  80285. var scene = this.getScene();
  80286. if (scene) {
  80287. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80288. }
  80289. },
  80290. enumerable: true,
  80291. configurable: true
  80292. });
  80293. /**
  80294. * Occurs when the file is raw .hdr file.
  80295. */
  80296. HDRCubeTexture.prototype.loadTexture = function () {
  80297. var _this = this;
  80298. var callback = function (buffer) {
  80299. var scene = _this.getScene();
  80300. if (!scene) {
  80301. return null;
  80302. }
  80303. // Extract the raw linear data.
  80304. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80305. // Generate harmonics if needed.
  80306. if (_this._generateHarmonics) {
  80307. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80308. _this.sphericalPolynomial = sphericalPolynomial;
  80309. }
  80310. var results = [];
  80311. var byteArray = null;
  80312. // Push each faces.
  80313. for (var j = 0; j < 6; j++) {
  80314. // Create uintarray fallback.
  80315. if (!scene.getEngine().getCaps().textureFloat) {
  80316. // 3 channels of 1 bytes per pixel in bytes.
  80317. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80318. byteArray = new Uint8Array(byteBuffer);
  80319. }
  80320. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80321. // If special cases.
  80322. if (_this.gammaSpace || byteArray) {
  80323. for (var i = 0; i < _this._size * _this._size; i++) {
  80324. // Put in gamma space if requested.
  80325. if (_this.gammaSpace) {
  80326. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80327. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80328. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80329. }
  80330. // Convert to int texture for fallback.
  80331. if (byteArray) {
  80332. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80333. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80334. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80335. // May use luminance instead if the result is not accurate.
  80336. var max = Math.max(Math.max(r, g), b);
  80337. if (max > 255) {
  80338. var scale = 255 / max;
  80339. r *= scale;
  80340. g *= scale;
  80341. b *= scale;
  80342. }
  80343. byteArray[(i * 3) + 0] = r;
  80344. byteArray[(i * 3) + 1] = g;
  80345. byteArray[(i * 3) + 2] = b;
  80346. }
  80347. }
  80348. }
  80349. if (byteArray) {
  80350. results.push(byteArray);
  80351. }
  80352. else {
  80353. results.push(dataFace);
  80354. }
  80355. }
  80356. return results;
  80357. };
  80358. var scene = this.getScene();
  80359. if (scene) {
  80360. 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, null, this._onLoad, this._onError);
  80361. }
  80362. };
  80363. HDRCubeTexture.prototype.clone = function () {
  80364. var scene = this.getScene();
  80365. if (!scene) {
  80366. return this;
  80367. }
  80368. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80369. // Base texture
  80370. newTexture.level = this.level;
  80371. newTexture.wrapU = this.wrapU;
  80372. newTexture.wrapV = this.wrapV;
  80373. newTexture.coordinatesIndex = this.coordinatesIndex;
  80374. newTexture.coordinatesMode = this.coordinatesMode;
  80375. return newTexture;
  80376. };
  80377. // Methods
  80378. HDRCubeTexture.prototype.delayLoad = function () {
  80379. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80380. return;
  80381. }
  80382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80383. this._texture = this._getFromCache(this.url, this._noMipmap);
  80384. if (!this._texture) {
  80385. this.loadTexture();
  80386. }
  80387. };
  80388. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80389. return this._textureMatrix;
  80390. };
  80391. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80392. this._textureMatrix = value;
  80393. };
  80394. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80395. var texture = null;
  80396. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80397. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80398. texture.name = parsedTexture.name;
  80399. texture.hasAlpha = parsedTexture.hasAlpha;
  80400. texture.level = parsedTexture.level;
  80401. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80402. texture.isBlocking = parsedTexture.isBlocking;
  80403. }
  80404. if (texture) {
  80405. if (parsedTexture.boundingBoxPosition) {
  80406. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80407. }
  80408. if (parsedTexture.boundingBoxSize) {
  80409. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80410. }
  80411. if (parsedTexture.rotationY) {
  80412. texture.rotationY = parsedTexture.rotationY;
  80413. }
  80414. }
  80415. return texture;
  80416. };
  80417. HDRCubeTexture.prototype.serialize = function () {
  80418. if (!this.name) {
  80419. return null;
  80420. }
  80421. var serializationObject = {};
  80422. serializationObject.name = this.name;
  80423. serializationObject.hasAlpha = this.hasAlpha;
  80424. serializationObject.isCube = true;
  80425. serializationObject.level = this.level;
  80426. serializationObject.size = this._size;
  80427. serializationObject.coordinatesMode = this.coordinatesMode;
  80428. serializationObject.useInGammaSpace = this.gammaSpace;
  80429. serializationObject.generateHarmonics = this._generateHarmonics;
  80430. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80431. serializationObject.noMipmap = this._noMipmap;
  80432. serializationObject.isBlocking = this._isBlocking;
  80433. serializationObject.rotationY = this._rotationY;
  80434. return serializationObject;
  80435. };
  80436. HDRCubeTexture._facesMapping = [
  80437. "right",
  80438. "left",
  80439. "up",
  80440. "down",
  80441. "front",
  80442. "back"
  80443. ];
  80444. return HDRCubeTexture;
  80445. }(BABYLON.BaseTexture));
  80446. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80447. })(BABYLON || (BABYLON = {}));
  80448. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80449. var BABYLON;
  80450. (function (BABYLON) {
  80451. var IndexedVector2 = /** @class */ (function (_super) {
  80452. __extends(IndexedVector2, _super);
  80453. function IndexedVector2(original, index) {
  80454. var _this = _super.call(this, original.x, original.y) || this;
  80455. _this.index = index;
  80456. return _this;
  80457. }
  80458. return IndexedVector2;
  80459. }(BABYLON.Vector2));
  80460. var PolygonPoints = /** @class */ (function () {
  80461. function PolygonPoints() {
  80462. this.elements = new Array();
  80463. }
  80464. PolygonPoints.prototype.add = function (originalPoints) {
  80465. var _this = this;
  80466. var result = new Array();
  80467. originalPoints.forEach(function (point) {
  80468. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80469. var newPoint = new IndexedVector2(point, _this.elements.length);
  80470. result.push(newPoint);
  80471. _this.elements.push(newPoint);
  80472. }
  80473. });
  80474. return result;
  80475. };
  80476. PolygonPoints.prototype.computeBounds = function () {
  80477. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80478. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80479. this.elements.forEach(function (point) {
  80480. // x
  80481. if (point.x < lmin.x) {
  80482. lmin.x = point.x;
  80483. }
  80484. else if (point.x > lmax.x) {
  80485. lmax.x = point.x;
  80486. }
  80487. // y
  80488. if (point.y < lmin.y) {
  80489. lmin.y = point.y;
  80490. }
  80491. else if (point.y > lmax.y) {
  80492. lmax.y = point.y;
  80493. }
  80494. });
  80495. return {
  80496. min: lmin,
  80497. max: lmax,
  80498. width: lmax.x - lmin.x,
  80499. height: lmax.y - lmin.y
  80500. };
  80501. };
  80502. return PolygonPoints;
  80503. }());
  80504. var Polygon = /** @class */ (function () {
  80505. function Polygon() {
  80506. }
  80507. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80508. return [
  80509. new BABYLON.Vector2(xmin, ymin),
  80510. new BABYLON.Vector2(xmax, ymin),
  80511. new BABYLON.Vector2(xmax, ymax),
  80512. new BABYLON.Vector2(xmin, ymax)
  80513. ];
  80514. };
  80515. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80516. if (cx === void 0) { cx = 0; }
  80517. if (cy === void 0) { cy = 0; }
  80518. if (numberOfSides === void 0) { numberOfSides = 32; }
  80519. var result = new Array();
  80520. var angle = 0;
  80521. var increment = (Math.PI * 2) / numberOfSides;
  80522. for (var i = 0; i < numberOfSides; i++) {
  80523. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80524. angle -= increment;
  80525. }
  80526. return result;
  80527. };
  80528. Polygon.Parse = function (input) {
  80529. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80530. var i, result = [];
  80531. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80532. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80533. }
  80534. return result;
  80535. };
  80536. Polygon.StartingAt = function (x, y) {
  80537. return BABYLON.Path2.StartingAt(x, y);
  80538. };
  80539. return Polygon;
  80540. }());
  80541. BABYLON.Polygon = Polygon;
  80542. var PolygonMeshBuilder = /** @class */ (function () {
  80543. function PolygonMeshBuilder(name, contours, scene) {
  80544. this._points = new PolygonPoints();
  80545. this._outlinepoints = new PolygonPoints();
  80546. this._holes = new Array();
  80547. this._epoints = new Array();
  80548. this._eholes = new Array();
  80549. this._name = name;
  80550. this._scene = scene;
  80551. var points;
  80552. if (contours instanceof BABYLON.Path2) {
  80553. points = contours.getPoints();
  80554. }
  80555. else {
  80556. points = contours;
  80557. }
  80558. this._addToepoint(points);
  80559. this._points.add(points);
  80560. this._outlinepoints.add(points);
  80561. if (typeof earcut === 'undefined') {
  80562. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80563. }
  80564. }
  80565. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80566. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80567. var p = points_1[_i];
  80568. this._epoints.push(p.x, p.y);
  80569. }
  80570. };
  80571. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80572. this._points.add(hole);
  80573. var holepoints = new PolygonPoints();
  80574. holepoints.add(hole);
  80575. this._holes.push(holepoints);
  80576. this._eholes.push(this._epoints.length / 2);
  80577. this._addToepoint(hole);
  80578. return this;
  80579. };
  80580. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80581. var _this = this;
  80582. if (updatable === void 0) { updatable = false; }
  80583. if (depth === void 0) { depth = 0; }
  80584. var result = new BABYLON.Mesh(this._name, this._scene);
  80585. var normals = new Array();
  80586. var positions = new Array();
  80587. var uvs = new Array();
  80588. var bounds = this._points.computeBounds();
  80589. this._points.elements.forEach(function (p) {
  80590. normals.push(0, 1.0, 0);
  80591. positions.push(p.x, 0, p.y);
  80592. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80593. });
  80594. var indices = new Array();
  80595. var res = earcut(this._epoints, this._eholes, 2);
  80596. for (var i = 0; i < res.length; i++) {
  80597. indices.push(res[i]);
  80598. }
  80599. if (depth > 0) {
  80600. var positionscount = (positions.length / 3); //get the current pointcount
  80601. this._points.elements.forEach(function (p) {
  80602. normals.push(0, -1.0, 0);
  80603. positions.push(p.x, -depth, p.y);
  80604. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80605. });
  80606. var totalCount = indices.length;
  80607. for (var i = 0; i < totalCount; i += 3) {
  80608. var i0 = indices[i + 0];
  80609. var i1 = indices[i + 1];
  80610. var i2 = indices[i + 2];
  80611. indices.push(i2 + positionscount);
  80612. indices.push(i1 + positionscount);
  80613. indices.push(i0 + positionscount);
  80614. }
  80615. //Add the sides
  80616. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80617. this._holes.forEach(function (hole) {
  80618. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80619. });
  80620. }
  80621. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80622. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80623. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80624. result.setIndices(indices);
  80625. return result;
  80626. };
  80627. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80628. var StartIndex = positions.length / 3;
  80629. var ulength = 0;
  80630. for (var i = 0; i < points.elements.length; i++) {
  80631. var p = points.elements[i];
  80632. var p1;
  80633. if ((i + 1) > points.elements.length - 1) {
  80634. p1 = points.elements[0];
  80635. }
  80636. else {
  80637. p1 = points.elements[i + 1];
  80638. }
  80639. positions.push(p.x, 0, p.y);
  80640. positions.push(p.x, -depth, p.y);
  80641. positions.push(p1.x, 0, p1.y);
  80642. positions.push(p1.x, -depth, p1.y);
  80643. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80644. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80645. var v3 = v2.subtract(v1);
  80646. var v4 = new BABYLON.Vector3(0, 1, 0);
  80647. var vn = BABYLON.Vector3.Cross(v3, v4);
  80648. vn = vn.normalize();
  80649. uvs.push(ulength / bounds.width, 0);
  80650. uvs.push(ulength / bounds.width, 1);
  80651. ulength += v3.length();
  80652. uvs.push((ulength / bounds.width), 0);
  80653. uvs.push((ulength / bounds.width), 1);
  80654. if (!flip) {
  80655. normals.push(-vn.x, -vn.y, -vn.z);
  80656. normals.push(-vn.x, -vn.y, -vn.z);
  80657. normals.push(-vn.x, -vn.y, -vn.z);
  80658. normals.push(-vn.x, -vn.y, -vn.z);
  80659. indices.push(StartIndex);
  80660. indices.push(StartIndex + 1);
  80661. indices.push(StartIndex + 2);
  80662. indices.push(StartIndex + 1);
  80663. indices.push(StartIndex + 3);
  80664. indices.push(StartIndex + 2);
  80665. }
  80666. else {
  80667. normals.push(vn.x, vn.y, vn.z);
  80668. normals.push(vn.x, vn.y, vn.z);
  80669. normals.push(vn.x, vn.y, vn.z);
  80670. normals.push(vn.x, vn.y, vn.z);
  80671. indices.push(StartIndex);
  80672. indices.push(StartIndex + 2);
  80673. indices.push(StartIndex + 1);
  80674. indices.push(StartIndex + 1);
  80675. indices.push(StartIndex + 2);
  80676. indices.push(StartIndex + 3);
  80677. }
  80678. StartIndex += 4;
  80679. }
  80680. ;
  80681. };
  80682. return PolygonMeshBuilder;
  80683. }());
  80684. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80685. })(BABYLON || (BABYLON = {}));
  80686. //# sourceMappingURL=babylon.polygonMesh.js.map
  80687. var BABYLON;
  80688. (function (BABYLON) {
  80689. // Unique ID when we import meshes from Babylon to CSG
  80690. var currentCSGMeshId = 0;
  80691. // # class Vertex
  80692. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80693. // one to provide additional features like texture coordinates and vertex
  80694. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80695. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80696. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80697. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80698. // is not used anywhere else.
  80699. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80700. var Vertex = /** @class */ (function () {
  80701. function Vertex(pos, normal, uv) {
  80702. this.pos = pos;
  80703. this.normal = normal;
  80704. this.uv = uv;
  80705. }
  80706. Vertex.prototype.clone = function () {
  80707. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80708. };
  80709. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80710. // orientation of a polygon is flipped.
  80711. Vertex.prototype.flip = function () {
  80712. this.normal = this.normal.scale(-1);
  80713. };
  80714. // Create a new vertex between this vertex and `other` by linearly
  80715. // interpolating all properties using a parameter of `t`. Subclasses should
  80716. // override this to interpolate additional properties.
  80717. Vertex.prototype.interpolate = function (other, t) {
  80718. 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));
  80719. };
  80720. return Vertex;
  80721. }());
  80722. // # class Plane
  80723. // Represents a plane in 3D space.
  80724. var Plane = /** @class */ (function () {
  80725. function Plane(normal, w) {
  80726. this.normal = normal;
  80727. this.w = w;
  80728. }
  80729. Plane.FromPoints = function (a, b, c) {
  80730. var v0 = c.subtract(a);
  80731. var v1 = b.subtract(a);
  80732. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80733. return null;
  80734. }
  80735. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80736. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80737. };
  80738. Plane.prototype.clone = function () {
  80739. return new Plane(this.normal.clone(), this.w);
  80740. };
  80741. Plane.prototype.flip = function () {
  80742. this.normal.scaleInPlace(-1);
  80743. this.w = -this.w;
  80744. };
  80745. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80746. // fragments in the appropriate lists. Coplanar polygons go into either
  80747. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80748. // respect to this plane. Polygons in front or in back of this plane go into
  80749. // either `front` or `back`.
  80750. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80751. var COPLANAR = 0;
  80752. var FRONT = 1;
  80753. var BACK = 2;
  80754. var SPANNING = 3;
  80755. // Classify each point as well as the entire polygon into one of the above
  80756. // four classes.
  80757. var polygonType = 0;
  80758. var types = [];
  80759. var i;
  80760. var t;
  80761. for (i = 0; i < polygon.vertices.length; i++) {
  80762. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80763. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80764. polygonType |= type;
  80765. types.push(type);
  80766. }
  80767. // Put the polygon in the correct list, splitting it when necessary.
  80768. switch (polygonType) {
  80769. case COPLANAR:
  80770. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80771. break;
  80772. case FRONT:
  80773. front.push(polygon);
  80774. break;
  80775. case BACK:
  80776. back.push(polygon);
  80777. break;
  80778. case SPANNING:
  80779. var f = [], b = [];
  80780. for (i = 0; i < polygon.vertices.length; i++) {
  80781. var j = (i + 1) % polygon.vertices.length;
  80782. var ti = types[i], tj = types[j];
  80783. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80784. if (ti !== BACK)
  80785. f.push(vi);
  80786. if (ti !== FRONT)
  80787. b.push(ti !== BACK ? vi.clone() : vi);
  80788. if ((ti | tj) === SPANNING) {
  80789. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80790. var v = vi.interpolate(vj, t);
  80791. f.push(v);
  80792. b.push(v.clone());
  80793. }
  80794. }
  80795. var poly;
  80796. if (f.length >= 3) {
  80797. poly = new Polygon(f, polygon.shared);
  80798. if (poly.plane)
  80799. front.push(poly);
  80800. }
  80801. if (b.length >= 3) {
  80802. poly = new Polygon(b, polygon.shared);
  80803. if (poly.plane)
  80804. back.push(poly);
  80805. }
  80806. break;
  80807. }
  80808. };
  80809. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80810. // point is on the plane.
  80811. Plane.EPSILON = 1e-5;
  80812. return Plane;
  80813. }());
  80814. // # class Polygon
  80815. // Represents a convex polygon. The vertices used to initialize a polygon must
  80816. // be coplanar and form a convex loop.
  80817. //
  80818. // Each convex polygon has a `shared` property, which is shared between all
  80819. // polygons that are clones of each other or were split from the same polygon.
  80820. // This can be used to define per-polygon properties (such as surface color).
  80821. var Polygon = /** @class */ (function () {
  80822. function Polygon(vertices, shared) {
  80823. this.vertices = vertices;
  80824. this.shared = shared;
  80825. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80826. }
  80827. Polygon.prototype.clone = function () {
  80828. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80829. return new Polygon(vertices, this.shared);
  80830. };
  80831. Polygon.prototype.flip = function () {
  80832. this.vertices.reverse().map(function (v) { v.flip(); });
  80833. this.plane.flip();
  80834. };
  80835. return Polygon;
  80836. }());
  80837. // # class Node
  80838. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80839. // by picking a polygon to split along. That polygon (and all other coplanar
  80840. // polygons) are added directly to that node and the other polygons are added to
  80841. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80842. // no distinction between internal and leaf nodes.
  80843. var Node = /** @class */ (function () {
  80844. function Node(polygons) {
  80845. this.plane = null;
  80846. this.front = null;
  80847. this.back = null;
  80848. this.polygons = new Array();
  80849. if (polygons) {
  80850. this.build(polygons);
  80851. }
  80852. }
  80853. Node.prototype.clone = function () {
  80854. var node = new Node();
  80855. node.plane = this.plane && this.plane.clone();
  80856. node.front = this.front && this.front.clone();
  80857. node.back = this.back && this.back.clone();
  80858. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80859. return node;
  80860. };
  80861. // Convert solid space to empty space and empty space to solid space.
  80862. Node.prototype.invert = function () {
  80863. for (var i = 0; i < this.polygons.length; i++) {
  80864. this.polygons[i].flip();
  80865. }
  80866. if (this.plane) {
  80867. this.plane.flip();
  80868. }
  80869. if (this.front) {
  80870. this.front.invert();
  80871. }
  80872. if (this.back) {
  80873. this.back.invert();
  80874. }
  80875. var temp = this.front;
  80876. this.front = this.back;
  80877. this.back = temp;
  80878. };
  80879. // Recursively remove all polygons in `polygons` that are inside this BSP
  80880. // tree.
  80881. Node.prototype.clipPolygons = function (polygons) {
  80882. if (!this.plane)
  80883. return polygons.slice();
  80884. var front = new Array(), back = new Array();
  80885. for (var i = 0; i < polygons.length; i++) {
  80886. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80887. }
  80888. if (this.front) {
  80889. front = this.front.clipPolygons(front);
  80890. }
  80891. if (this.back) {
  80892. back = this.back.clipPolygons(back);
  80893. }
  80894. else {
  80895. back = [];
  80896. }
  80897. return front.concat(back);
  80898. };
  80899. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80900. // `bsp`.
  80901. Node.prototype.clipTo = function (bsp) {
  80902. this.polygons = bsp.clipPolygons(this.polygons);
  80903. if (this.front)
  80904. this.front.clipTo(bsp);
  80905. if (this.back)
  80906. this.back.clipTo(bsp);
  80907. };
  80908. // Return a list of all polygons in this BSP tree.
  80909. Node.prototype.allPolygons = function () {
  80910. var polygons = this.polygons.slice();
  80911. if (this.front)
  80912. polygons = polygons.concat(this.front.allPolygons());
  80913. if (this.back)
  80914. polygons = polygons.concat(this.back.allPolygons());
  80915. return polygons;
  80916. };
  80917. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80918. // new polygons are filtered down to the bottom of the tree and become new
  80919. // nodes there. Each set of polygons is partitioned using the first polygon
  80920. // (no heuristic is used to pick a good split).
  80921. Node.prototype.build = function (polygons) {
  80922. if (!polygons.length)
  80923. return;
  80924. if (!this.plane)
  80925. this.plane = polygons[0].plane.clone();
  80926. var front = new Array(), back = new Array();
  80927. for (var i = 0; i < polygons.length; i++) {
  80928. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80929. }
  80930. if (front.length) {
  80931. if (!this.front)
  80932. this.front = new Node();
  80933. this.front.build(front);
  80934. }
  80935. if (back.length) {
  80936. if (!this.back)
  80937. this.back = new Node();
  80938. this.back.build(back);
  80939. }
  80940. };
  80941. return Node;
  80942. }());
  80943. var CSG = /** @class */ (function () {
  80944. function CSG() {
  80945. this.polygons = new Array();
  80946. }
  80947. // Convert BABYLON.Mesh to BABYLON.CSG
  80948. CSG.FromMesh = function (mesh) {
  80949. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80950. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80951. if (mesh instanceof BABYLON.Mesh) {
  80952. mesh.computeWorldMatrix(true);
  80953. matrix = mesh.getWorldMatrix();
  80954. meshPosition = mesh.position.clone();
  80955. meshRotation = mesh.rotation.clone();
  80956. if (mesh.rotationQuaternion) {
  80957. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80958. }
  80959. meshScaling = mesh.scaling.clone();
  80960. }
  80961. else {
  80962. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80963. }
  80964. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80965. var subMeshes = mesh.subMeshes;
  80966. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80967. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80968. vertices = [];
  80969. for (var j = 0; j < 3; j++) {
  80970. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80971. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80972. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80973. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80974. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80975. vertex = new Vertex(position, normal, uv);
  80976. vertices.push(vertex);
  80977. }
  80978. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80979. // To handle the case of degenerated triangle
  80980. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80981. if (polygon.plane)
  80982. polygons.push(polygon);
  80983. }
  80984. }
  80985. var csg = CSG.FromPolygons(polygons);
  80986. csg.matrix = matrix;
  80987. csg.position = meshPosition;
  80988. csg.rotation = meshRotation;
  80989. csg.scaling = meshScaling;
  80990. csg.rotationQuaternion = meshRotationQuaternion;
  80991. currentCSGMeshId++;
  80992. return csg;
  80993. };
  80994. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80995. CSG.FromPolygons = function (polygons) {
  80996. var csg = new CSG();
  80997. csg.polygons = polygons;
  80998. return csg;
  80999. };
  81000. CSG.prototype.clone = function () {
  81001. var csg = new CSG();
  81002. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81003. csg.copyTransformAttributes(this);
  81004. return csg;
  81005. };
  81006. CSG.prototype.union = function (csg) {
  81007. var a = new Node(this.clone().polygons);
  81008. var b = new Node(csg.clone().polygons);
  81009. a.clipTo(b);
  81010. b.clipTo(a);
  81011. b.invert();
  81012. b.clipTo(a);
  81013. b.invert();
  81014. a.build(b.allPolygons());
  81015. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81016. };
  81017. CSG.prototype.unionInPlace = function (csg) {
  81018. var a = new Node(this.polygons);
  81019. var b = new Node(csg.polygons);
  81020. a.clipTo(b);
  81021. b.clipTo(a);
  81022. b.invert();
  81023. b.clipTo(a);
  81024. b.invert();
  81025. a.build(b.allPolygons());
  81026. this.polygons = a.allPolygons();
  81027. };
  81028. CSG.prototype.subtract = function (csg) {
  81029. var a = new Node(this.clone().polygons);
  81030. var b = new Node(csg.clone().polygons);
  81031. a.invert();
  81032. a.clipTo(b);
  81033. b.clipTo(a);
  81034. b.invert();
  81035. b.clipTo(a);
  81036. b.invert();
  81037. a.build(b.allPolygons());
  81038. a.invert();
  81039. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81040. };
  81041. CSG.prototype.subtractInPlace = function (csg) {
  81042. var a = new Node(this.polygons);
  81043. var b = new Node(csg.polygons);
  81044. a.invert();
  81045. a.clipTo(b);
  81046. b.clipTo(a);
  81047. b.invert();
  81048. b.clipTo(a);
  81049. b.invert();
  81050. a.build(b.allPolygons());
  81051. a.invert();
  81052. this.polygons = a.allPolygons();
  81053. };
  81054. CSG.prototype.intersect = function (csg) {
  81055. var a = new Node(this.clone().polygons);
  81056. var b = new Node(csg.clone().polygons);
  81057. a.invert();
  81058. b.clipTo(a);
  81059. b.invert();
  81060. a.clipTo(b);
  81061. b.clipTo(a);
  81062. a.build(b.allPolygons());
  81063. a.invert();
  81064. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81065. };
  81066. CSG.prototype.intersectInPlace = function (csg) {
  81067. var a = new Node(this.polygons);
  81068. var b = new Node(csg.polygons);
  81069. a.invert();
  81070. b.clipTo(a);
  81071. b.invert();
  81072. a.clipTo(b);
  81073. b.clipTo(a);
  81074. a.build(b.allPolygons());
  81075. a.invert();
  81076. this.polygons = a.allPolygons();
  81077. };
  81078. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81079. // not modified.
  81080. CSG.prototype.inverse = function () {
  81081. var csg = this.clone();
  81082. csg.inverseInPlace();
  81083. return csg;
  81084. };
  81085. CSG.prototype.inverseInPlace = function () {
  81086. this.polygons.map(function (p) { p.flip(); });
  81087. };
  81088. // This is used to keep meshes transformations so they can be restored
  81089. // when we build back a Babylon Mesh
  81090. // NB : All CSG operations are performed in world coordinates
  81091. CSG.prototype.copyTransformAttributes = function (csg) {
  81092. this.matrix = csg.matrix;
  81093. this.position = csg.position;
  81094. this.rotation = csg.rotation;
  81095. this.scaling = csg.scaling;
  81096. this.rotationQuaternion = csg.rotationQuaternion;
  81097. return this;
  81098. };
  81099. // Build Raw mesh from CSG
  81100. // Coordinates here are in world space
  81101. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81102. var matrix = this.matrix.clone();
  81103. matrix.invert();
  81104. 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;
  81105. if (keepSubMeshes) {
  81106. // Sort Polygons, since subMeshes are indices range
  81107. polygons.sort(function (a, b) {
  81108. if (a.shared.meshId === b.shared.meshId) {
  81109. return a.shared.subMeshId - b.shared.subMeshId;
  81110. }
  81111. else {
  81112. return a.shared.meshId - b.shared.meshId;
  81113. }
  81114. });
  81115. }
  81116. for (var i = 0, il = polygons.length; i < il; i++) {
  81117. polygon = polygons[i];
  81118. // Building SubMeshes
  81119. if (!subMesh_dict[polygon.shared.meshId]) {
  81120. subMesh_dict[polygon.shared.meshId] = {};
  81121. }
  81122. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81123. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81124. indexStart: +Infinity,
  81125. indexEnd: -Infinity,
  81126. materialIndex: polygon.shared.materialIndex
  81127. };
  81128. }
  81129. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81130. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81131. polygonIndices[0] = 0;
  81132. polygonIndices[1] = j - 1;
  81133. polygonIndices[2] = j;
  81134. for (var k = 0; k < 3; k++) {
  81135. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81136. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81137. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81138. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81139. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81140. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81141. // Check if 2 points can be merged
  81142. if (!(typeof vertex_idx !== 'undefined' &&
  81143. normals[vertex_idx * 3] === localNormal.x &&
  81144. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81145. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81146. uvs[vertex_idx * 2] === uv.x &&
  81147. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81148. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81149. uvs.push(uv.x, uv.y);
  81150. normals.push(normal.x, normal.y, normal.z);
  81151. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81152. }
  81153. indices.push(vertex_idx);
  81154. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81155. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81156. currentIndex++;
  81157. }
  81158. }
  81159. }
  81160. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81161. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81162. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81163. mesh.setIndices(indices, null);
  81164. if (keepSubMeshes) {
  81165. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81166. var materialIndexOffset = 0, materialMaxIndex;
  81167. mesh.subMeshes = new Array();
  81168. for (var m in subMesh_dict) {
  81169. materialMaxIndex = -1;
  81170. for (var sm in subMesh_dict[m]) {
  81171. subMesh_obj = subMesh_dict[m][sm];
  81172. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81173. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81174. }
  81175. materialIndexOffset += ++materialMaxIndex;
  81176. }
  81177. }
  81178. return mesh;
  81179. };
  81180. // Build Mesh from CSG taking material and transforms into account
  81181. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81182. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81183. mesh.material = material;
  81184. mesh.position.copyFrom(this.position);
  81185. mesh.rotation.copyFrom(this.rotation);
  81186. if (this.rotationQuaternion) {
  81187. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81188. }
  81189. mesh.scaling.copyFrom(this.scaling);
  81190. mesh.computeWorldMatrix(true);
  81191. return mesh;
  81192. };
  81193. return CSG;
  81194. }());
  81195. BABYLON.CSG = CSG;
  81196. })(BABYLON || (BABYLON = {}));
  81197. //# sourceMappingURL=babylon.csg.js.map
  81198. var BABYLON;
  81199. (function (BABYLON) {
  81200. var LensFlare = /** @class */ (function () {
  81201. function LensFlare(size, position, color, imgUrl, system) {
  81202. this.size = size;
  81203. this.position = position;
  81204. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81205. this.color = color || new BABYLON.Color3(1, 1, 1);
  81206. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81207. this._system = system;
  81208. system.lensFlares.push(this);
  81209. }
  81210. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81211. return new LensFlare(size, position, color, imgUrl, system);
  81212. };
  81213. LensFlare.prototype.dispose = function () {
  81214. if (this.texture) {
  81215. this.texture.dispose();
  81216. }
  81217. // Remove from scene
  81218. var index = this._system.lensFlares.indexOf(this);
  81219. this._system.lensFlares.splice(index, 1);
  81220. };
  81221. ;
  81222. return LensFlare;
  81223. }());
  81224. BABYLON.LensFlare = LensFlare;
  81225. })(BABYLON || (BABYLON = {}));
  81226. //# sourceMappingURL=babylon.lensFlare.js.map
  81227. var BABYLON;
  81228. (function (BABYLON) {
  81229. var LensFlareSystem = /** @class */ (function () {
  81230. function LensFlareSystem(name, emitter, scene) {
  81231. this.name = name;
  81232. this.lensFlares = new Array();
  81233. this.borderLimit = 300;
  81234. this.viewportBorder = 0;
  81235. this.layerMask = 0x0FFFFFFF;
  81236. this._vertexBuffers = {};
  81237. this._isEnabled = true;
  81238. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81239. this._emitter = emitter;
  81240. this.id = name;
  81241. scene.lensFlareSystems.push(this);
  81242. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81243. var engine = scene.getEngine();
  81244. // VBO
  81245. var vertices = [];
  81246. vertices.push(1, 1);
  81247. vertices.push(-1, 1);
  81248. vertices.push(-1, -1);
  81249. vertices.push(1, -1);
  81250. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81251. // Indices
  81252. var indices = [];
  81253. indices.push(0);
  81254. indices.push(1);
  81255. indices.push(2);
  81256. indices.push(0);
  81257. indices.push(2);
  81258. indices.push(3);
  81259. this._indexBuffer = engine.createIndexBuffer(indices);
  81260. // Effects
  81261. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81262. }
  81263. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81264. get: function () {
  81265. return this._isEnabled;
  81266. },
  81267. set: function (value) {
  81268. this._isEnabled = value;
  81269. },
  81270. enumerable: true,
  81271. configurable: true
  81272. });
  81273. LensFlareSystem.prototype.getScene = function () {
  81274. return this._scene;
  81275. };
  81276. LensFlareSystem.prototype.getEmitter = function () {
  81277. return this._emitter;
  81278. };
  81279. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81280. this._emitter = newEmitter;
  81281. };
  81282. LensFlareSystem.prototype.getEmitterPosition = function () {
  81283. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81284. };
  81285. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81286. var position = this.getEmitterPosition();
  81287. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81288. this._positionX = position.x;
  81289. this._positionY = position.y;
  81290. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81291. if (this.viewportBorder > 0) {
  81292. globalViewport.x -= this.viewportBorder;
  81293. globalViewport.y -= this.viewportBorder;
  81294. globalViewport.width += this.viewportBorder * 2;
  81295. globalViewport.height += this.viewportBorder * 2;
  81296. position.x += this.viewportBorder;
  81297. position.y += this.viewportBorder;
  81298. this._positionX += this.viewportBorder;
  81299. this._positionY += this.viewportBorder;
  81300. }
  81301. if (position.z > 0) {
  81302. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81303. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81304. return true;
  81305. }
  81306. return true;
  81307. }
  81308. return false;
  81309. };
  81310. LensFlareSystem.prototype._isVisible = function () {
  81311. if (!this._isEnabled || !this._scene.activeCamera) {
  81312. return false;
  81313. }
  81314. var emitterPosition = this.getEmitterPosition();
  81315. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81316. var distance = direction.length();
  81317. direction.normalize();
  81318. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81319. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81320. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81321. };
  81322. LensFlareSystem.prototype.render = function () {
  81323. if (!this._effect.isReady() || !this._scene.activeCamera)
  81324. return false;
  81325. var engine = this._scene.getEngine();
  81326. var viewport = this._scene.activeCamera.viewport;
  81327. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81328. // Position
  81329. if (!this.computeEffectivePosition(globalViewport)) {
  81330. return false;
  81331. }
  81332. // Visibility
  81333. if (!this._isVisible()) {
  81334. return false;
  81335. }
  81336. // Intensity
  81337. var awayX;
  81338. var awayY;
  81339. if (this._positionX < this.borderLimit + globalViewport.x) {
  81340. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81341. }
  81342. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81343. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81344. }
  81345. else {
  81346. awayX = 0;
  81347. }
  81348. if (this._positionY < this.borderLimit + globalViewport.y) {
  81349. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81350. }
  81351. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81352. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81353. }
  81354. else {
  81355. awayY = 0;
  81356. }
  81357. var away = (awayX > awayY) ? awayX : awayY;
  81358. away -= this.viewportBorder;
  81359. if (away > this.borderLimit) {
  81360. away = this.borderLimit;
  81361. }
  81362. var intensity = 1.0 - (away / this.borderLimit);
  81363. if (intensity < 0) {
  81364. return false;
  81365. }
  81366. if (intensity > 1.0) {
  81367. intensity = 1.0;
  81368. }
  81369. if (this.viewportBorder > 0) {
  81370. globalViewport.x += this.viewportBorder;
  81371. globalViewport.y += this.viewportBorder;
  81372. globalViewport.width -= this.viewportBorder * 2;
  81373. globalViewport.height -= this.viewportBorder * 2;
  81374. this._positionX -= this.viewportBorder;
  81375. this._positionY -= this.viewportBorder;
  81376. }
  81377. // Position
  81378. var centerX = globalViewport.x + globalViewport.width / 2;
  81379. var centerY = globalViewport.y + globalViewport.height / 2;
  81380. var distX = centerX - this._positionX;
  81381. var distY = centerY - this._positionY;
  81382. // Effects
  81383. engine.enableEffect(this._effect);
  81384. engine.setState(false);
  81385. engine.setDepthBuffer(false);
  81386. // VBOs
  81387. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81388. // Flares
  81389. for (var index = 0; index < this.lensFlares.length; index++) {
  81390. var flare = this.lensFlares[index];
  81391. engine.setAlphaMode(flare.alphaMode);
  81392. var x = centerX - (distX * flare.position);
  81393. var y = centerY - (distY * flare.position);
  81394. var cw = flare.size;
  81395. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81396. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81397. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81398. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81399. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81400. // Texture
  81401. this._effect.setTexture("textureSampler", flare.texture);
  81402. // Color
  81403. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81404. // Draw order
  81405. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81406. }
  81407. engine.setDepthBuffer(true);
  81408. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81409. return true;
  81410. };
  81411. LensFlareSystem.prototype.dispose = function () {
  81412. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81413. if (vertexBuffer) {
  81414. vertexBuffer.dispose();
  81415. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81416. }
  81417. if (this._indexBuffer) {
  81418. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81419. this._indexBuffer = null;
  81420. }
  81421. while (this.lensFlares.length) {
  81422. this.lensFlares[0].dispose();
  81423. }
  81424. // Remove from scene
  81425. var index = this._scene.lensFlareSystems.indexOf(this);
  81426. this._scene.lensFlareSystems.splice(index, 1);
  81427. };
  81428. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81429. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81430. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81431. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81432. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81433. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81434. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81435. var parsedFlare = parsedLensFlareSystem.flares[index];
  81436. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81437. }
  81438. return lensFlareSystem;
  81439. };
  81440. LensFlareSystem.prototype.serialize = function () {
  81441. var serializationObject = {};
  81442. serializationObject.id = this.id;
  81443. serializationObject.name = this.name;
  81444. serializationObject.emitterId = this.getEmitter().id;
  81445. serializationObject.borderLimit = this.borderLimit;
  81446. serializationObject.flares = [];
  81447. for (var index = 0; index < this.lensFlares.length; index++) {
  81448. var flare = this.lensFlares[index];
  81449. serializationObject.flares.push({
  81450. size: flare.size,
  81451. position: flare.position,
  81452. color: flare.color.asArray(),
  81453. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81454. });
  81455. }
  81456. return serializationObject;
  81457. };
  81458. return LensFlareSystem;
  81459. }());
  81460. BABYLON.LensFlareSystem = LensFlareSystem;
  81461. })(BABYLON || (BABYLON = {}));
  81462. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81463. var BABYLON;
  81464. (function (BABYLON) {
  81465. /**
  81466. * This is a holder class for the physics joint created by the physics plugin.
  81467. * It holds a set of functions to control the underlying joint.
  81468. */
  81469. var PhysicsJoint = /** @class */ (function () {
  81470. function PhysicsJoint(type, jointData) {
  81471. this.type = type;
  81472. this.jointData = jointData;
  81473. jointData.nativeParams = jointData.nativeParams || {};
  81474. }
  81475. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81476. get: function () {
  81477. return this._physicsJoint;
  81478. },
  81479. set: function (newJoint) {
  81480. if (this._physicsJoint) {
  81481. //remove from the wolrd
  81482. }
  81483. this._physicsJoint = newJoint;
  81484. },
  81485. enumerable: true,
  81486. configurable: true
  81487. });
  81488. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81489. set: function (physicsPlugin) {
  81490. this._physicsPlugin = physicsPlugin;
  81491. },
  81492. enumerable: true,
  81493. configurable: true
  81494. });
  81495. /**
  81496. * Execute a function that is physics-plugin specific.
  81497. * @param {Function} func the function that will be executed.
  81498. * It accepts two parameters: the physics world and the physics joint.
  81499. */
  81500. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81501. func(this._physicsPlugin.world, this._physicsJoint);
  81502. };
  81503. //TODO check if the native joints are the same
  81504. //Joint Types
  81505. PhysicsJoint.DistanceJoint = 0;
  81506. PhysicsJoint.HingeJoint = 1;
  81507. PhysicsJoint.BallAndSocketJoint = 2;
  81508. PhysicsJoint.WheelJoint = 3;
  81509. PhysicsJoint.SliderJoint = 4;
  81510. //OIMO
  81511. PhysicsJoint.PrismaticJoint = 5;
  81512. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81513. PhysicsJoint.UniversalJoint = 6;
  81514. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81515. //Cannon
  81516. //Similar to a Ball-Joint. Different in params
  81517. PhysicsJoint.PointToPointJoint = 8;
  81518. //Cannon only at the moment
  81519. PhysicsJoint.SpringJoint = 9;
  81520. PhysicsJoint.LockJoint = 10;
  81521. return PhysicsJoint;
  81522. }());
  81523. BABYLON.PhysicsJoint = PhysicsJoint;
  81524. /**
  81525. * A class representing a physics distance joint.
  81526. */
  81527. var DistanceJoint = /** @class */ (function (_super) {
  81528. __extends(DistanceJoint, _super);
  81529. function DistanceJoint(jointData) {
  81530. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81531. }
  81532. /**
  81533. * Update the predefined distance.
  81534. */
  81535. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81536. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81537. };
  81538. return DistanceJoint;
  81539. }(PhysicsJoint));
  81540. BABYLON.DistanceJoint = DistanceJoint;
  81541. var MotorEnabledJoint = /** @class */ (function (_super) {
  81542. __extends(MotorEnabledJoint, _super);
  81543. function MotorEnabledJoint(type, jointData) {
  81544. return _super.call(this, type, jointData) || this;
  81545. }
  81546. /**
  81547. * Set the motor values.
  81548. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81549. * @param {number} force the force to apply
  81550. * @param {number} maxForce max force for this motor.
  81551. */
  81552. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81553. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81554. };
  81555. /**
  81556. * Set the motor's limits.
  81557. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81558. */
  81559. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81560. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81561. };
  81562. return MotorEnabledJoint;
  81563. }(PhysicsJoint));
  81564. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81565. /**
  81566. * This class represents a single hinge physics joint
  81567. */
  81568. var HingeJoint = /** @class */ (function (_super) {
  81569. __extends(HingeJoint, _super);
  81570. function HingeJoint(jointData) {
  81571. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81572. }
  81573. /**
  81574. * Set the motor values.
  81575. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81576. * @param {number} force the force to apply
  81577. * @param {number} maxForce max force for this motor.
  81578. */
  81579. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81580. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81581. };
  81582. /**
  81583. * Set the motor's limits.
  81584. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81585. */
  81586. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81587. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81588. };
  81589. return HingeJoint;
  81590. }(MotorEnabledJoint));
  81591. BABYLON.HingeJoint = HingeJoint;
  81592. /**
  81593. * This class represents a dual hinge physics joint (same as wheel joint)
  81594. */
  81595. var Hinge2Joint = /** @class */ (function (_super) {
  81596. __extends(Hinge2Joint, _super);
  81597. function Hinge2Joint(jointData) {
  81598. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81599. }
  81600. /**
  81601. * Set the motor values.
  81602. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81603. * @param {number} force the force to apply
  81604. * @param {number} maxForce max force for this motor.
  81605. * @param {motorIndex} the motor's index, 0 or 1.
  81606. */
  81607. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81608. if (motorIndex === void 0) { motorIndex = 0; }
  81609. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81610. };
  81611. /**
  81612. * Set the motor limits.
  81613. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81614. * @param {number} upperLimit the upper limit
  81615. * @param {number} lowerLimit lower limit
  81616. * @param {motorIndex} the motor's index, 0 or 1.
  81617. */
  81618. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81619. if (motorIndex === void 0) { motorIndex = 0; }
  81620. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81621. };
  81622. return Hinge2Joint;
  81623. }(MotorEnabledJoint));
  81624. BABYLON.Hinge2Joint = Hinge2Joint;
  81625. })(BABYLON || (BABYLON = {}));
  81626. //# sourceMappingURL=babylon.physicsJoint.js.map
  81627. var BABYLON;
  81628. (function (BABYLON) {
  81629. var PhysicsImpostor = /** @class */ (function () {
  81630. function PhysicsImpostor(object, type, _options, _scene) {
  81631. if (_options === void 0) { _options = { mass: 0 }; }
  81632. var _this = this;
  81633. this.object = object;
  81634. this.type = type;
  81635. this._options = _options;
  81636. this._scene = _scene;
  81637. this._bodyUpdateRequired = false;
  81638. this._onBeforePhysicsStepCallbacks = new Array();
  81639. this._onAfterPhysicsStepCallbacks = new Array();
  81640. this._onPhysicsCollideCallbacks = [];
  81641. this._deltaPosition = BABYLON.Vector3.Zero();
  81642. this._isDisposed = false;
  81643. //temp variables for parent rotation calculations
  81644. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81645. this._tmpQuat = new BABYLON.Quaternion();
  81646. this._tmpQuat2 = new BABYLON.Quaternion();
  81647. /**
  81648. * this function is executed by the physics engine.
  81649. */
  81650. this.beforeStep = function () {
  81651. if (!_this._physicsEngine) {
  81652. return;
  81653. }
  81654. _this.object.translate(_this._deltaPosition, -1);
  81655. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81656. _this.object.computeWorldMatrix(false);
  81657. if (_this.object.parent && _this.object.rotationQuaternion) {
  81658. _this.getParentsRotation();
  81659. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81660. }
  81661. else {
  81662. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81663. }
  81664. if (!_this._options.disableBidirectionalTransformation) {
  81665. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81666. }
  81667. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81668. func(_this);
  81669. });
  81670. };
  81671. /**
  81672. * this function is executed by the physics engine.
  81673. */
  81674. this.afterStep = function () {
  81675. if (!_this._physicsEngine) {
  81676. return;
  81677. }
  81678. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81679. func(_this);
  81680. });
  81681. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81682. // object has now its world rotation. needs to be converted to local.
  81683. if (_this.object.parent && _this.object.rotationQuaternion) {
  81684. _this.getParentsRotation();
  81685. _this._tmpQuat.conjugateInPlace();
  81686. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81687. }
  81688. // take the position set and make it the absolute position of this object.
  81689. _this.object.setAbsolutePosition(_this.object.position);
  81690. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81691. _this.object.translate(_this._deltaPosition, 1);
  81692. };
  81693. /**
  81694. * Legacy collision detection event support
  81695. */
  81696. this.onCollideEvent = null;
  81697. //event and body object due to cannon's event-based architecture.
  81698. this.onCollide = function (e) {
  81699. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81700. return;
  81701. }
  81702. if (!_this._physicsEngine) {
  81703. return;
  81704. }
  81705. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81706. if (otherImpostor) {
  81707. // Legacy collision detection event support
  81708. if (_this.onCollideEvent) {
  81709. _this.onCollideEvent(_this, otherImpostor);
  81710. }
  81711. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81712. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81713. }).forEach(function (obj) {
  81714. obj.callback(_this, otherImpostor);
  81715. });
  81716. }
  81717. };
  81718. //sanity check!
  81719. if (!this.object) {
  81720. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81721. return;
  81722. }
  81723. //legacy support for old syntax.
  81724. if (!this._scene && object.getScene) {
  81725. this._scene = object.getScene();
  81726. }
  81727. if (!this._scene) {
  81728. return;
  81729. }
  81730. this._physicsEngine = this._scene.getPhysicsEngine();
  81731. if (!this._physicsEngine) {
  81732. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81733. }
  81734. else {
  81735. //set the object's quaternion, if not set
  81736. if (!this.object.rotationQuaternion) {
  81737. if (this.object.rotation) {
  81738. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81739. }
  81740. else {
  81741. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81742. }
  81743. }
  81744. //default options params
  81745. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81746. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81747. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81748. this._joints = [];
  81749. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81750. if (!this.object.parent || this._options.ignoreParent) {
  81751. this._init();
  81752. }
  81753. else if (this.object.parent.physicsImpostor) {
  81754. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81755. }
  81756. }
  81757. }
  81758. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81759. get: function () {
  81760. return this._isDisposed;
  81761. },
  81762. enumerable: true,
  81763. configurable: true
  81764. });
  81765. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81766. get: function () {
  81767. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81768. },
  81769. set: function (value) {
  81770. this.setMass(value);
  81771. },
  81772. enumerable: true,
  81773. configurable: true
  81774. });
  81775. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81776. get: function () {
  81777. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81778. },
  81779. set: function (value) {
  81780. if (!this._physicsEngine) {
  81781. return;
  81782. }
  81783. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81784. },
  81785. enumerable: true,
  81786. configurable: true
  81787. });
  81788. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81789. get: function () {
  81790. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81791. },
  81792. set: function (value) {
  81793. if (!this._physicsEngine) {
  81794. return;
  81795. }
  81796. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81797. },
  81798. enumerable: true,
  81799. configurable: true
  81800. });
  81801. /**
  81802. * This function will completly initialize this impostor.
  81803. * It will create a new body - but only if this mesh has no parent.
  81804. * If it has, this impostor will not be used other than to define the impostor
  81805. * of the child mesh.
  81806. */
  81807. PhysicsImpostor.prototype._init = function () {
  81808. if (!this._physicsEngine) {
  81809. return;
  81810. }
  81811. this._physicsEngine.removeImpostor(this);
  81812. this.physicsBody = null;
  81813. this._parent = this._parent || this._getPhysicsParent();
  81814. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81815. this._physicsEngine.addImpostor(this);
  81816. }
  81817. };
  81818. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81819. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81820. var parentMesh = this.object.parent;
  81821. return parentMesh.physicsImpostor;
  81822. }
  81823. return null;
  81824. };
  81825. /**
  81826. * Should a new body be generated.
  81827. */
  81828. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81829. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81830. };
  81831. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81832. this.forceUpdate();
  81833. };
  81834. /**
  81835. * Force a regeneration of this or the parent's impostor's body.
  81836. * Use under cautious - This will remove all joints already implemented.
  81837. */
  81838. PhysicsImpostor.prototype.forceUpdate = function () {
  81839. this._init();
  81840. if (this.parent && !this._options.ignoreParent) {
  81841. this.parent.forceUpdate();
  81842. }
  81843. };
  81844. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81845. /*public get mesh(): AbstractMesh {
  81846. return this._mesh;
  81847. }*/
  81848. /**
  81849. * Gets the body that holds this impostor. Either its own, or its parent.
  81850. */
  81851. get: function () {
  81852. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81853. },
  81854. /**
  81855. * Set the physics body. Used mainly by the physics engine/plugin
  81856. */
  81857. set: function (physicsBody) {
  81858. if (this._physicsBody && this._physicsEngine) {
  81859. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81860. }
  81861. this._physicsBody = physicsBody;
  81862. this.resetUpdateFlags();
  81863. },
  81864. enumerable: true,
  81865. configurable: true
  81866. });
  81867. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81868. get: function () {
  81869. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81870. },
  81871. set: function (value) {
  81872. this._parent = value;
  81873. },
  81874. enumerable: true,
  81875. configurable: true
  81876. });
  81877. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81878. this._bodyUpdateRequired = false;
  81879. };
  81880. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81881. if (this.object.getBoundingInfo) {
  81882. var q = this.object.rotationQuaternion;
  81883. //reset rotation
  81884. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81885. //calculate the world matrix with no rotation
  81886. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81887. var boundingInfo = this.object.getBoundingInfo();
  81888. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81889. //bring back the rotation
  81890. this.object.rotationQuaternion = q;
  81891. //calculate the world matrix with the new rotation
  81892. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81893. return size;
  81894. }
  81895. else {
  81896. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81897. }
  81898. };
  81899. PhysicsImpostor.prototype.getObjectCenter = function () {
  81900. if (this.object.getBoundingInfo) {
  81901. var boundingInfo = this.object.getBoundingInfo();
  81902. return boundingInfo.boundingBox.centerWorld;
  81903. }
  81904. else {
  81905. return this.object.position;
  81906. }
  81907. };
  81908. /**
  81909. * Get a specific parametes from the options parameter.
  81910. */
  81911. PhysicsImpostor.prototype.getParam = function (paramName) {
  81912. return this._options[paramName];
  81913. };
  81914. /**
  81915. * Sets a specific parameter in the options given to the physics plugin
  81916. */
  81917. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81918. this._options[paramName] = value;
  81919. this._bodyUpdateRequired = true;
  81920. };
  81921. /**
  81922. * Specifically change the body's mass option. Won't recreate the physics body object
  81923. */
  81924. PhysicsImpostor.prototype.setMass = function (mass) {
  81925. if (this.getParam("mass") !== mass) {
  81926. this.setParam("mass", mass);
  81927. }
  81928. if (this._physicsEngine) {
  81929. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81930. }
  81931. };
  81932. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81933. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81934. };
  81935. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81936. if (this._physicsEngine) {
  81937. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81938. }
  81939. };
  81940. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81941. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81942. };
  81943. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81944. if (this._physicsEngine) {
  81945. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81946. }
  81947. };
  81948. /**
  81949. * Execute a function with the physics plugin native code.
  81950. * Provide a function the will have two variables - the world object and the physics body object.
  81951. */
  81952. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81953. if (this._physicsEngine) {
  81954. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81955. }
  81956. };
  81957. /**
  81958. * Register a function that will be executed before the physics world is stepping forward.
  81959. */
  81960. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81961. this._onBeforePhysicsStepCallbacks.push(func);
  81962. };
  81963. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81964. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81965. if (index > -1) {
  81966. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81967. }
  81968. else {
  81969. BABYLON.Tools.Warn("Function to remove was not found");
  81970. }
  81971. };
  81972. /**
  81973. * Register a function that will be executed after the physics step
  81974. */
  81975. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81976. this._onAfterPhysicsStepCallbacks.push(func);
  81977. };
  81978. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81979. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81980. if (index > -1) {
  81981. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81982. }
  81983. else {
  81984. BABYLON.Tools.Warn("Function to remove was not found");
  81985. }
  81986. };
  81987. /**
  81988. * register a function that will be executed when this impostor collides against a different body.
  81989. */
  81990. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81991. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81992. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81993. };
  81994. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81995. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81996. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81997. if (index > -1) {
  81998. this._onPhysicsCollideCallbacks.splice(index, 1);
  81999. }
  82000. else {
  82001. BABYLON.Tools.Warn("Function to remove was not found");
  82002. }
  82003. };
  82004. PhysicsImpostor.prototype.getParentsRotation = function () {
  82005. var parent = this.object.parent;
  82006. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82007. while (parent) {
  82008. if (parent.rotationQuaternion) {
  82009. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82010. }
  82011. else {
  82012. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82013. }
  82014. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82015. parent = parent.parent;
  82016. }
  82017. return this._tmpQuat;
  82018. };
  82019. /**
  82020. * Apply a force
  82021. */
  82022. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82023. if (this._physicsEngine) {
  82024. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82025. }
  82026. return this;
  82027. };
  82028. /**
  82029. * Apply an impulse
  82030. */
  82031. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82032. if (this._physicsEngine) {
  82033. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82034. }
  82035. return this;
  82036. };
  82037. /**
  82038. * A help function to create a joint.
  82039. */
  82040. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82041. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82042. this.addJoint(otherImpostor, joint);
  82043. return this;
  82044. };
  82045. /**
  82046. * Add a joint to this impostor with a different impostor.
  82047. */
  82048. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82049. this._joints.push({
  82050. otherImpostor: otherImpostor,
  82051. joint: joint
  82052. });
  82053. if (this._physicsEngine) {
  82054. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82055. }
  82056. return this;
  82057. };
  82058. /**
  82059. * Will keep this body still, in a sleep mode.
  82060. */
  82061. PhysicsImpostor.prototype.sleep = function () {
  82062. if (this._physicsEngine) {
  82063. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82064. }
  82065. return this;
  82066. };
  82067. /**
  82068. * Wake the body up.
  82069. */
  82070. PhysicsImpostor.prototype.wakeUp = function () {
  82071. if (this._physicsEngine) {
  82072. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82073. }
  82074. return this;
  82075. };
  82076. PhysicsImpostor.prototype.clone = function (newObject) {
  82077. if (!newObject)
  82078. return null;
  82079. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82080. };
  82081. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82082. var _this = this;
  82083. //no dispose if no physics engine is available.
  82084. if (!this._physicsEngine) {
  82085. return;
  82086. }
  82087. this._joints.forEach(function (j) {
  82088. if (_this._physicsEngine) {
  82089. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82090. }
  82091. });
  82092. //dispose the physics body
  82093. this._physicsEngine.removeImpostor(this);
  82094. if (this.parent) {
  82095. this.parent.forceUpdate();
  82096. }
  82097. else {
  82098. /*this._object.getChildMeshes().forEach(function(mesh) {
  82099. if (mesh.physicsImpostor) {
  82100. if (disposeChildren) {
  82101. mesh.physicsImpostor.dispose();
  82102. mesh.physicsImpostor = null;
  82103. }
  82104. }
  82105. })*/
  82106. }
  82107. this._isDisposed = true;
  82108. };
  82109. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82110. this._deltaPosition.copyFrom(position);
  82111. };
  82112. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82113. if (!this._deltaRotation) {
  82114. this._deltaRotation = new BABYLON.Quaternion();
  82115. }
  82116. this._deltaRotation.copyFrom(rotation);
  82117. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82118. };
  82119. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82120. if (this._physicsEngine) {
  82121. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82122. }
  82123. return this;
  82124. };
  82125. PhysicsImpostor.prototype.getRadius = function () {
  82126. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82127. };
  82128. /**
  82129. * Sync a bone with this impostor
  82130. * @param bone The bone to sync to the impostor.
  82131. * @param boneMesh The mesh that the bone is influencing.
  82132. * @param jointPivot The pivot of the joint / bone in local space.
  82133. * @param distToJoint Optional distance from the impostor to the joint.
  82134. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82135. */
  82136. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82137. var tempVec = PhysicsImpostor._tmpVecs[0];
  82138. var mesh = this.object;
  82139. if (mesh.rotationQuaternion) {
  82140. if (adjustRotation) {
  82141. var tempQuat = PhysicsImpostor._tmpQuat;
  82142. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82143. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82144. }
  82145. else {
  82146. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82147. }
  82148. }
  82149. tempVec.x = 0;
  82150. tempVec.y = 0;
  82151. tempVec.z = 0;
  82152. if (jointPivot) {
  82153. tempVec.x = jointPivot.x;
  82154. tempVec.y = jointPivot.y;
  82155. tempVec.z = jointPivot.z;
  82156. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82157. if (distToJoint === undefined || distToJoint === null) {
  82158. distToJoint = jointPivot.length();
  82159. }
  82160. tempVec.x *= distToJoint;
  82161. tempVec.y *= distToJoint;
  82162. tempVec.z *= distToJoint;
  82163. }
  82164. if (bone.getParent()) {
  82165. tempVec.addInPlace(mesh.getAbsolutePosition());
  82166. bone.setAbsolutePosition(tempVec, boneMesh);
  82167. }
  82168. else {
  82169. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82170. boneMesh.position.x -= tempVec.x;
  82171. boneMesh.position.y -= tempVec.y;
  82172. boneMesh.position.z -= tempVec.z;
  82173. }
  82174. };
  82175. /**
  82176. * Sync impostor to a bone
  82177. * @param bone The bone that the impostor will be synced to.
  82178. * @param boneMesh The mesh that the bone is influencing.
  82179. * @param jointPivot The pivot of the joint / bone in local space.
  82180. * @param distToJoint Optional distance from the impostor to the joint.
  82181. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82182. * @param boneAxis Optional vector3 axis the bone is aligned with
  82183. */
  82184. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82185. var mesh = this.object;
  82186. if (mesh.rotationQuaternion) {
  82187. if (adjustRotation) {
  82188. var tempQuat = PhysicsImpostor._tmpQuat;
  82189. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82190. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82191. }
  82192. else {
  82193. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82194. }
  82195. }
  82196. var pos = PhysicsImpostor._tmpVecs[0];
  82197. var boneDir = PhysicsImpostor._tmpVecs[1];
  82198. if (!boneAxis) {
  82199. boneAxis = PhysicsImpostor._tmpVecs[2];
  82200. boneAxis.x = 0;
  82201. boneAxis.y = 1;
  82202. boneAxis.z = 0;
  82203. }
  82204. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82205. bone.getAbsolutePositionToRef(boneMesh, pos);
  82206. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82207. distToJoint = jointPivot.length();
  82208. }
  82209. if (distToJoint !== undefined && distToJoint !== null) {
  82210. pos.x += boneDir.x * distToJoint;
  82211. pos.y += boneDir.y * distToJoint;
  82212. pos.z += boneDir.z * distToJoint;
  82213. }
  82214. mesh.setAbsolutePosition(pos);
  82215. };
  82216. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82217. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82218. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82219. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82220. //Impostor types
  82221. PhysicsImpostor.NoImpostor = 0;
  82222. PhysicsImpostor.SphereImpostor = 1;
  82223. PhysicsImpostor.BoxImpostor = 2;
  82224. PhysicsImpostor.PlaneImpostor = 3;
  82225. PhysicsImpostor.MeshImpostor = 4;
  82226. PhysicsImpostor.CylinderImpostor = 7;
  82227. PhysicsImpostor.ParticleImpostor = 8;
  82228. PhysicsImpostor.HeightmapImpostor = 9;
  82229. return PhysicsImpostor;
  82230. }());
  82231. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82232. })(BABYLON || (BABYLON = {}));
  82233. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82234. var BABYLON;
  82235. (function (BABYLON) {
  82236. var PhysicsEngine = /** @class */ (function () {
  82237. function PhysicsEngine(gravity, _physicsPlugin) {
  82238. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82239. this._physicsPlugin = _physicsPlugin;
  82240. //new methods and parameters
  82241. this._impostors = [];
  82242. this._joints = [];
  82243. if (!this._physicsPlugin.isSupported()) {
  82244. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82245. + "Please make sure it is included.");
  82246. }
  82247. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82248. this.setGravity(gravity);
  82249. this.setTimeStep();
  82250. }
  82251. PhysicsEngine.prototype.setGravity = function (gravity) {
  82252. this.gravity = gravity;
  82253. this._physicsPlugin.setGravity(this.gravity);
  82254. };
  82255. /**
  82256. * Set the time step of the physics engine.
  82257. * default is 1/60.
  82258. * To slow it down, enter 1/600 for example.
  82259. * To speed it up, 1/30
  82260. * @param {number} newTimeStep the new timestep to apply to this world.
  82261. */
  82262. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82263. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82264. this._physicsPlugin.setTimeStep(newTimeStep);
  82265. };
  82266. /**
  82267. * Get the time step of the physics engine.
  82268. */
  82269. PhysicsEngine.prototype.getTimeStep = function () {
  82270. return this._physicsPlugin.getTimeStep();
  82271. };
  82272. PhysicsEngine.prototype.dispose = function () {
  82273. this._impostors.forEach(function (impostor) {
  82274. impostor.dispose();
  82275. });
  82276. this._physicsPlugin.dispose();
  82277. };
  82278. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82279. return this._physicsPlugin.name;
  82280. };
  82281. /**
  82282. * Adding a new impostor for the impostor tracking.
  82283. * This will be done by the impostor itself.
  82284. * @param {PhysicsImpostor} impostor the impostor to add
  82285. */
  82286. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82287. impostor.uniqueId = this._impostors.push(impostor);
  82288. //if no parent, generate the body
  82289. if (!impostor.parent) {
  82290. this._physicsPlugin.generatePhysicsBody(impostor);
  82291. }
  82292. };
  82293. /**
  82294. * Remove an impostor from the engine.
  82295. * This impostor and its mesh will not longer be updated by the physics engine.
  82296. * @param {PhysicsImpostor} impostor the impostor to remove
  82297. */
  82298. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82299. var index = this._impostors.indexOf(impostor);
  82300. if (index > -1) {
  82301. var removed = this._impostors.splice(index, 1);
  82302. //Is it needed?
  82303. if (removed.length) {
  82304. //this will also remove it from the world.
  82305. removed[0].physicsBody = null;
  82306. }
  82307. }
  82308. };
  82309. /**
  82310. * Add a joint to the physics engine
  82311. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82312. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82313. * @param {PhysicsJoint} the joint that will connect both impostors.
  82314. */
  82315. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82316. var impostorJoint = {
  82317. mainImpostor: mainImpostor,
  82318. connectedImpostor: connectedImpostor,
  82319. joint: joint
  82320. };
  82321. joint.physicsPlugin = this._physicsPlugin;
  82322. this._joints.push(impostorJoint);
  82323. this._physicsPlugin.generateJoint(impostorJoint);
  82324. };
  82325. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82326. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82327. return (impostorJoint.connectedImpostor === connectedImpostor
  82328. && impostorJoint.joint === joint
  82329. && impostorJoint.mainImpostor === mainImpostor);
  82330. });
  82331. if (matchingJoints.length) {
  82332. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82333. //TODO remove it from the list as well
  82334. }
  82335. };
  82336. /**
  82337. * Called by the scene. no need to call it.
  82338. */
  82339. PhysicsEngine.prototype._step = function (delta) {
  82340. var _this = this;
  82341. //check if any mesh has no body / requires an update
  82342. this._impostors.forEach(function (impostor) {
  82343. if (impostor.isBodyInitRequired()) {
  82344. _this._physicsPlugin.generatePhysicsBody(impostor);
  82345. }
  82346. });
  82347. if (delta > 0.1) {
  82348. delta = 0.1;
  82349. }
  82350. else if (delta <= 0) {
  82351. delta = 1.0 / 60.0;
  82352. }
  82353. this._physicsPlugin.executeStep(delta, this._impostors);
  82354. };
  82355. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82356. return this._physicsPlugin;
  82357. };
  82358. PhysicsEngine.prototype.getImpostors = function () {
  82359. return this._impostors;
  82360. };
  82361. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82362. for (var i = 0; i < this._impostors.length; ++i) {
  82363. if (this._impostors[i].object === object) {
  82364. return this._impostors[i];
  82365. }
  82366. }
  82367. return null;
  82368. };
  82369. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82370. for (var i = 0; i < this._impostors.length; ++i) {
  82371. if (this._impostors[i].physicsBody === body) {
  82372. return this._impostors[i];
  82373. }
  82374. }
  82375. return null;
  82376. };
  82377. // Statics
  82378. PhysicsEngine.Epsilon = 0.001;
  82379. return PhysicsEngine;
  82380. }());
  82381. BABYLON.PhysicsEngine = PhysicsEngine;
  82382. })(BABYLON || (BABYLON = {}));
  82383. //# sourceMappingURL=babylon.physicsEngine.js.map
  82384. var BABYLON;
  82385. (function (BABYLON) {
  82386. var PhysicsHelper = /** @class */ (function () {
  82387. function PhysicsHelper(scene) {
  82388. this._scene = scene;
  82389. this._physicsEngine = this._scene.getPhysicsEngine();
  82390. if (!this._physicsEngine) {
  82391. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82392. }
  82393. }
  82394. /**
  82395. * @param {Vector3} origin the origin of the explosion
  82396. * @param {number} radius the explosion radius
  82397. * @param {number} strength the explosion strength
  82398. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82399. */
  82400. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82401. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82402. if (!this._physicsEngine) {
  82403. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82404. return null;
  82405. }
  82406. var impostors = this._physicsEngine.getImpostors();
  82407. if (impostors.length === 0) {
  82408. return null;
  82409. }
  82410. var event = new PhysicsRadialExplosionEvent(this._scene);
  82411. impostors.forEach(function (impostor) {
  82412. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82413. if (!impostorForceAndContactPoint) {
  82414. return;
  82415. }
  82416. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82417. });
  82418. event.dispose(false);
  82419. return event;
  82420. };
  82421. /**
  82422. * @param {Vector3} origin the origin of the explosion
  82423. * @param {number} radius the explosion radius
  82424. * @param {number} strength the explosion strength
  82425. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82426. */
  82427. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82428. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82429. if (!this._physicsEngine) {
  82430. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82431. return null;
  82432. }
  82433. var impostors = this._physicsEngine.getImpostors();
  82434. if (impostors.length === 0) {
  82435. return null;
  82436. }
  82437. var event = new PhysicsRadialExplosionEvent(this._scene);
  82438. impostors.forEach(function (impostor) {
  82439. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82440. if (!impostorForceAndContactPoint) {
  82441. return;
  82442. }
  82443. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82444. });
  82445. event.dispose(false);
  82446. return event;
  82447. };
  82448. /**
  82449. * @param {Vector3} origin the origin of the explosion
  82450. * @param {number} radius the explosion radius
  82451. * @param {number} strength the explosion strength
  82452. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82453. */
  82454. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82455. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82456. if (!this._physicsEngine) {
  82457. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82458. return null;
  82459. }
  82460. var impostors = this._physicsEngine.getImpostors();
  82461. if (impostors.length === 0) {
  82462. return null;
  82463. }
  82464. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82465. event.dispose(false);
  82466. return event;
  82467. };
  82468. /**
  82469. * @param {Vector3} origin the origin of the updraft
  82470. * @param {number} radius the radius of the updraft
  82471. * @param {number} strength the strength of the updraft
  82472. * @param {number} height the height of the updraft
  82473. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82474. */
  82475. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82476. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82477. if (!this._physicsEngine) {
  82478. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82479. return null;
  82480. }
  82481. if (this._physicsEngine.getImpostors().length === 0) {
  82482. return null;
  82483. }
  82484. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82485. event.dispose(false);
  82486. return event;
  82487. };
  82488. /**
  82489. * @param {Vector3} origin the of the vortex
  82490. * @param {number} radius the radius of the vortex
  82491. * @param {number} strength the strength of the vortex
  82492. * @param {number} height the height of the vortex
  82493. */
  82494. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82495. if (!this._physicsEngine) {
  82496. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82497. return null;
  82498. }
  82499. if (this._physicsEngine.getImpostors().length === 0) {
  82500. return null;
  82501. }
  82502. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82503. event.dispose(false);
  82504. return event;
  82505. };
  82506. return PhysicsHelper;
  82507. }());
  82508. BABYLON.PhysicsHelper = PhysicsHelper;
  82509. /***** Radial explosion *****/
  82510. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82511. function PhysicsRadialExplosionEvent(scene) {
  82512. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82513. this._rays = [];
  82514. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82515. this._scene = scene;
  82516. }
  82517. /**
  82518. * Returns the data related to the radial explosion event (sphere & rays).
  82519. * @returns {PhysicsRadialExplosionEventData}
  82520. */
  82521. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82522. this._dataFetched = true;
  82523. return {
  82524. sphere: this._sphere,
  82525. rays: this._rays,
  82526. };
  82527. };
  82528. /**
  82529. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82530. * @param impostor
  82531. * @param {Vector3} origin the origin of the explosion
  82532. * @param {number} radius the explosion radius
  82533. * @param {number} strength the explosion strength
  82534. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82535. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82536. */
  82537. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82538. if (impostor.mass === 0) {
  82539. return null;
  82540. }
  82541. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82542. return null;
  82543. }
  82544. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82545. return null;
  82546. }
  82547. var impostorObjectCenter = impostor.getObjectCenter();
  82548. var direction = impostorObjectCenter.subtract(origin);
  82549. var ray = new BABYLON.Ray(origin, direction, radius);
  82550. this._rays.push(ray);
  82551. var hit = ray.intersectsMesh(impostor.object);
  82552. var contactPoint = hit.pickedPoint;
  82553. if (!contactPoint) {
  82554. return null;
  82555. }
  82556. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82557. if (distanceFromOrigin > radius) {
  82558. return null;
  82559. }
  82560. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82561. ? strength
  82562. : strength * (1 - (distanceFromOrigin / radius));
  82563. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82564. return { force: force, contactPoint: contactPoint };
  82565. };
  82566. /**
  82567. * Disposes the sphere.
  82568. * @param {bolean} force
  82569. */
  82570. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82571. var _this = this;
  82572. if (force === void 0) { force = true; }
  82573. if (force) {
  82574. this._sphere.dispose();
  82575. }
  82576. else {
  82577. setTimeout(function () {
  82578. if (!_this._dataFetched) {
  82579. _this._sphere.dispose();
  82580. }
  82581. }, 0);
  82582. }
  82583. };
  82584. /*** Helpers ***/
  82585. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82586. if (!this._sphere) {
  82587. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82588. this._sphere.isVisible = false;
  82589. }
  82590. };
  82591. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82592. var impostorObject = impostor.object;
  82593. this._prepareSphere();
  82594. this._sphere.position = origin;
  82595. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82596. this._sphere._updateBoundingInfo();
  82597. this._sphere.computeWorldMatrix(true);
  82598. return this._sphere.intersectsMesh(impostorObject, true);
  82599. };
  82600. return PhysicsRadialExplosionEvent;
  82601. }());
  82602. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82603. /***** Gravitational Field *****/
  82604. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82605. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82606. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82607. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82608. this._physicsHelper = physicsHelper;
  82609. this._scene = scene;
  82610. this._origin = origin;
  82611. this._radius = radius;
  82612. this._strength = strength;
  82613. this._falloff = falloff;
  82614. this._tickCallback = this._tick.bind(this);
  82615. }
  82616. /**
  82617. * Returns the data related to the gravitational field event (sphere).
  82618. * @returns {PhysicsGravitationalFieldEventData}
  82619. */
  82620. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82621. this._dataFetched = true;
  82622. return {
  82623. sphere: this._sphere,
  82624. };
  82625. };
  82626. /**
  82627. * Enables the gravitational field.
  82628. */
  82629. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82630. this._tickCallback.call(this);
  82631. this._scene.registerBeforeRender(this._tickCallback);
  82632. };
  82633. /**
  82634. * Disables the gravitational field.
  82635. */
  82636. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82637. this._scene.unregisterBeforeRender(this._tickCallback);
  82638. };
  82639. /**
  82640. * Disposes the sphere.
  82641. * @param {bolean} force
  82642. */
  82643. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82644. var _this = this;
  82645. if (force === void 0) { force = true; }
  82646. if (force) {
  82647. this._sphere.dispose();
  82648. }
  82649. else {
  82650. setTimeout(function () {
  82651. if (!_this._dataFetched) {
  82652. _this._sphere.dispose();
  82653. }
  82654. }, 0);
  82655. }
  82656. };
  82657. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82658. // Since the params won't change, we fetch the event only once
  82659. if (this._sphere) {
  82660. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82661. }
  82662. else {
  82663. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82664. if (radialExplosionEvent) {
  82665. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82666. }
  82667. }
  82668. };
  82669. return PhysicsGravitationalFieldEvent;
  82670. }());
  82671. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82672. /***** Updraft *****/
  82673. var PhysicsUpdraftEvent = /** @class */ (function () {
  82674. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82675. this._scene = _scene;
  82676. this._origin = _origin;
  82677. this._radius = _radius;
  82678. this._strength = _strength;
  82679. this._height = _height;
  82680. this._updraftMode = _updraftMode;
  82681. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82682. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82683. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82684. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82685. this._physicsEngine = this._scene.getPhysicsEngine();
  82686. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82687. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82688. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82689. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82690. }
  82691. this._tickCallback = this._tick.bind(this);
  82692. }
  82693. /**
  82694. * Returns the data related to the updraft event (cylinder).
  82695. * @returns {PhysicsUpdraftEventData}
  82696. */
  82697. PhysicsUpdraftEvent.prototype.getData = function () {
  82698. this._dataFetched = true;
  82699. return {
  82700. cylinder: this._cylinder,
  82701. };
  82702. };
  82703. /**
  82704. * Enables the updraft.
  82705. */
  82706. PhysicsUpdraftEvent.prototype.enable = function () {
  82707. this._tickCallback.call(this);
  82708. this._scene.registerBeforeRender(this._tickCallback);
  82709. };
  82710. /**
  82711. * Disables the cortex.
  82712. */
  82713. PhysicsUpdraftEvent.prototype.disable = function () {
  82714. this._scene.unregisterBeforeRender(this._tickCallback);
  82715. };
  82716. /**
  82717. * Disposes the sphere.
  82718. * @param {bolean} force
  82719. */
  82720. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82721. var _this = this;
  82722. if (force === void 0) { force = true; }
  82723. if (force) {
  82724. this._cylinder.dispose();
  82725. }
  82726. else {
  82727. setTimeout(function () {
  82728. if (!_this._dataFetched) {
  82729. _this._cylinder.dispose();
  82730. }
  82731. }, 0);
  82732. }
  82733. };
  82734. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82735. if (impostor.mass === 0) {
  82736. return null;
  82737. }
  82738. if (!this._intersectsWithCylinder(impostor)) {
  82739. return null;
  82740. }
  82741. var impostorObjectCenter = impostor.getObjectCenter();
  82742. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82743. var direction = this._originDirection;
  82744. }
  82745. else {
  82746. var direction = impostorObjectCenter.subtract(this._originTop);
  82747. }
  82748. var multiplier = this._strength * -1;
  82749. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82750. return { force: force, contactPoint: impostorObjectCenter };
  82751. };
  82752. PhysicsUpdraftEvent.prototype._tick = function () {
  82753. var _this = this;
  82754. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82755. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82756. if (!impostorForceAndContactPoint) {
  82757. return;
  82758. }
  82759. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82760. });
  82761. };
  82762. /*** Helpers ***/
  82763. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82764. if (!this._cylinder) {
  82765. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82766. height: this._height,
  82767. diameter: this._radius * 2,
  82768. }, this._scene);
  82769. this._cylinder.isVisible = false;
  82770. }
  82771. };
  82772. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82773. var impostorObject = impostor.object;
  82774. this._prepareCylinder();
  82775. this._cylinder.position = this._cylinderPosition;
  82776. return this._cylinder.intersectsMesh(impostorObject, true);
  82777. };
  82778. return PhysicsUpdraftEvent;
  82779. }());
  82780. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82781. /***** Vortex *****/
  82782. var PhysicsVortexEvent = /** @class */ (function () {
  82783. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82784. this._scene = _scene;
  82785. this._origin = _origin;
  82786. this._radius = _radius;
  82787. this._strength = _strength;
  82788. this._height = _height;
  82789. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82790. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82791. this._updraftMultiplier = 0.02;
  82792. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82793. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82794. this._physicsEngine = this._scene.getPhysicsEngine();
  82795. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82796. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82797. this._tickCallback = this._tick.bind(this);
  82798. }
  82799. /**
  82800. * Returns the data related to the vortex event (cylinder).
  82801. * @returns {PhysicsVortexEventData}
  82802. */
  82803. PhysicsVortexEvent.prototype.getData = function () {
  82804. this._dataFetched = true;
  82805. return {
  82806. cylinder: this._cylinder,
  82807. };
  82808. };
  82809. /**
  82810. * Enables the vortex.
  82811. */
  82812. PhysicsVortexEvent.prototype.enable = function () {
  82813. this._tickCallback.call(this);
  82814. this._scene.registerBeforeRender(this._tickCallback);
  82815. };
  82816. /**
  82817. * Disables the cortex.
  82818. */
  82819. PhysicsVortexEvent.prototype.disable = function () {
  82820. this._scene.unregisterBeforeRender(this._tickCallback);
  82821. };
  82822. /**
  82823. * Disposes the sphere.
  82824. * @param {bolean} force
  82825. */
  82826. PhysicsVortexEvent.prototype.dispose = function (force) {
  82827. var _this = this;
  82828. if (force === void 0) { force = true; }
  82829. if (force) {
  82830. this._cylinder.dispose();
  82831. }
  82832. else {
  82833. setTimeout(function () {
  82834. if (!_this._dataFetched) {
  82835. _this._cylinder.dispose();
  82836. }
  82837. }, 0);
  82838. }
  82839. };
  82840. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82841. if (impostor.mass === 0) {
  82842. return null;
  82843. }
  82844. if (!this._intersectsWithCylinder(impostor)) {
  82845. return null;
  82846. }
  82847. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82848. return null;
  82849. }
  82850. var impostorObjectCenter = impostor.getObjectCenter();
  82851. 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)
  82852. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82853. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82854. var hit = ray.intersectsMesh(impostor.object);
  82855. var contactPoint = hit.pickedPoint;
  82856. if (!contactPoint) {
  82857. return null;
  82858. }
  82859. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82860. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82861. var directionToOrigin = contactPoint.normalize();
  82862. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82863. directionToOrigin = directionToOrigin.negate();
  82864. }
  82865. // TODO: find a more physically based solution
  82866. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82867. var forceX = directionToOrigin.x * this._strength / 8;
  82868. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82869. var forceZ = directionToOrigin.z * this._strength / 8;
  82870. }
  82871. else {
  82872. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82873. var forceY = this._originTop.y * this._updraftMultiplier;
  82874. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82875. }
  82876. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82877. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82878. return { force: force, contactPoint: impostorObjectCenter };
  82879. };
  82880. PhysicsVortexEvent.prototype._tick = function () {
  82881. var _this = this;
  82882. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82883. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82884. if (!impostorForceAndContactPoint) {
  82885. return;
  82886. }
  82887. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82888. });
  82889. };
  82890. /*** Helpers ***/
  82891. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82892. if (!this._cylinder) {
  82893. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82894. height: this._height,
  82895. diameter: this._radius * 2,
  82896. }, this._scene);
  82897. this._cylinder.isVisible = false;
  82898. }
  82899. };
  82900. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82901. var impostorObject = impostor.object;
  82902. this._prepareCylinder();
  82903. this._cylinder.position = this._cylinderPosition;
  82904. return this._cylinder.intersectsMesh(impostorObject, true);
  82905. };
  82906. return PhysicsVortexEvent;
  82907. }());
  82908. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82909. /***** Enums *****/
  82910. /**
  82911. * The strenght of the force in correspondence to the distance of the affected object
  82912. */
  82913. var PhysicsRadialImpulseFalloff;
  82914. (function (PhysicsRadialImpulseFalloff) {
  82915. /** Defines that impulse is constant in strength across it's whole radius */
  82916. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82917. /** DEfines that impulse gets weaker if it's further from the origin */
  82918. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82919. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82920. /**
  82921. * The strenght of the force in correspondence to the distance of the affected object
  82922. */
  82923. var PhysicsUpdraftMode;
  82924. (function (PhysicsUpdraftMode) {
  82925. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82926. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82927. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82928. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82929. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82930. })(BABYLON || (BABYLON = {}));
  82931. //# sourceMappingURL=babylon.physicsHelper.js.map
  82932. var BABYLON;
  82933. (function (BABYLON) {
  82934. var CannonJSPlugin = /** @class */ (function () {
  82935. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82936. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82937. if (iterations === void 0) { iterations = 10; }
  82938. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82939. this.name = "CannonJSPlugin";
  82940. this._physicsMaterials = new Array();
  82941. this._fixedTimeStep = 1 / 60;
  82942. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82943. this.BJSCANNON = CANNON;
  82944. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82945. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82946. this._tmpPosition = BABYLON.Vector3.Zero();
  82947. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82948. this._tmpUnityRotation = new BABYLON.Quaternion();
  82949. if (!this.isSupported()) {
  82950. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82951. return;
  82952. }
  82953. this._extendNamespace();
  82954. this.world = new this.BJSCANNON.World();
  82955. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82956. this.world.solver.iterations = iterations;
  82957. }
  82958. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82959. this.world.gravity.copy(gravity);
  82960. };
  82961. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82962. this._fixedTimeStep = timeStep;
  82963. };
  82964. CannonJSPlugin.prototype.getTimeStep = function () {
  82965. return this._fixedTimeStep;
  82966. };
  82967. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82968. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82969. };
  82970. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82971. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82972. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82973. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82974. };
  82975. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82976. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82977. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82978. impostor.physicsBody.applyForce(impulse, worldPoint);
  82979. };
  82980. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82981. //parent-child relationship. Does this impostor has a parent impostor?
  82982. if (impostor.parent) {
  82983. if (impostor.physicsBody) {
  82984. this.removePhysicsBody(impostor);
  82985. //TODO is that needed?
  82986. impostor.forceUpdate();
  82987. }
  82988. return;
  82989. }
  82990. //should a new body be created for this impostor?
  82991. if (impostor.isBodyInitRequired()) {
  82992. var shape = this._createShape(impostor);
  82993. //unregister events, if body is being changed
  82994. var oldBody = impostor.physicsBody;
  82995. if (oldBody) {
  82996. this.removePhysicsBody(impostor);
  82997. }
  82998. //create the body and material
  82999. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83000. var bodyCreationObject = {
  83001. mass: impostor.getParam("mass"),
  83002. material: material
  83003. };
  83004. // A simple extend, in case native options were used.
  83005. var nativeOptions = impostor.getParam("nativeOptions");
  83006. for (var key in nativeOptions) {
  83007. if (nativeOptions.hasOwnProperty(key)) {
  83008. bodyCreationObject[key] = nativeOptions[key];
  83009. }
  83010. }
  83011. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83012. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83013. this.world.addEventListener("preStep", impostor.beforeStep);
  83014. this.world.addEventListener("postStep", impostor.afterStep);
  83015. impostor.physicsBody.addShape(shape);
  83016. this.world.add(impostor.physicsBody);
  83017. //try to keep the body moving in the right direction by taking old properties.
  83018. //Should be tested!
  83019. if (oldBody) {
  83020. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83021. impostor.physicsBody[param].copy(oldBody[param]);
  83022. });
  83023. }
  83024. this._processChildMeshes(impostor);
  83025. }
  83026. //now update the body's transformation
  83027. this._updatePhysicsBodyTransformation(impostor);
  83028. };
  83029. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83030. var _this = this;
  83031. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83032. var currentRotation = mainImpostor.object.rotationQuaternion;
  83033. if (meshChildren.length) {
  83034. var processMesh = function (localPosition, mesh) {
  83035. if (!currentRotation || !mesh.rotationQuaternion) {
  83036. return;
  83037. }
  83038. var childImpostor = mesh.getPhysicsImpostor();
  83039. if (childImpostor) {
  83040. var parent = childImpostor.parent;
  83041. if (parent !== mainImpostor) {
  83042. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83043. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83044. if (childImpostor.physicsBody) {
  83045. _this.removePhysicsBody(childImpostor);
  83046. childImpostor.physicsBody = null;
  83047. }
  83048. childImpostor.parent = mainImpostor;
  83049. childImpostor.resetUpdateFlags();
  83050. 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));
  83051. //Add the mass of the children.
  83052. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83053. }
  83054. }
  83055. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83056. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83057. };
  83058. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83059. }
  83060. };
  83061. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83062. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83063. this.world.removeEventListener("preStep", impostor.beforeStep);
  83064. this.world.removeEventListener("postStep", impostor.afterStep);
  83065. this.world.remove(impostor.physicsBody);
  83066. };
  83067. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83068. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83069. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83070. if (!mainBody || !connectedBody) {
  83071. return;
  83072. }
  83073. var constraint;
  83074. var jointData = impostorJoint.joint.jointData;
  83075. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83076. var constraintData = {
  83077. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83078. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83079. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83080. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83081. maxForce: jointData.nativeParams.maxForce,
  83082. collideConnected: !!jointData.collision
  83083. };
  83084. switch (impostorJoint.joint.type) {
  83085. case BABYLON.PhysicsJoint.HingeJoint:
  83086. case BABYLON.PhysicsJoint.Hinge2Joint:
  83087. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83088. break;
  83089. case BABYLON.PhysicsJoint.DistanceJoint:
  83090. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83091. break;
  83092. case BABYLON.PhysicsJoint.SpringJoint:
  83093. var springData = jointData;
  83094. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83095. restLength: springData.length,
  83096. stiffness: springData.stiffness,
  83097. damping: springData.damping,
  83098. localAnchorA: constraintData.pivotA,
  83099. localAnchorB: constraintData.pivotB
  83100. });
  83101. break;
  83102. case BABYLON.PhysicsJoint.LockJoint:
  83103. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83104. break;
  83105. case BABYLON.PhysicsJoint.PointToPointJoint:
  83106. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83107. default:
  83108. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83109. break;
  83110. }
  83111. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83112. constraint.collideConnected = !!jointData.collision;
  83113. impostorJoint.joint.physicsJoint = constraint;
  83114. //don't add spring as constraint, as it is not one.
  83115. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83116. this.world.addConstraint(constraint);
  83117. }
  83118. else {
  83119. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83120. constraint.applyForce();
  83121. });
  83122. }
  83123. };
  83124. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83125. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83126. };
  83127. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83128. var index;
  83129. var mat;
  83130. for (index = 0; index < this._physicsMaterials.length; index++) {
  83131. mat = this._physicsMaterials[index];
  83132. if (mat.friction === friction && mat.restitution === restitution) {
  83133. return mat;
  83134. }
  83135. }
  83136. var currentMat = new this.BJSCANNON.Material(name);
  83137. currentMat.friction = friction;
  83138. currentMat.restitution = restitution;
  83139. this._physicsMaterials.push(currentMat);
  83140. return currentMat;
  83141. };
  83142. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83143. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83144. };
  83145. CannonJSPlugin.prototype._createShape = function (impostor) {
  83146. var object = impostor.object;
  83147. var returnValue;
  83148. var extendSize = impostor.getObjectExtendSize();
  83149. switch (impostor.type) {
  83150. case BABYLON.PhysicsImpostor.SphereImpostor:
  83151. var radiusX = extendSize.x;
  83152. var radiusY = extendSize.y;
  83153. var radiusZ = extendSize.z;
  83154. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83155. break;
  83156. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83157. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83158. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83159. break;
  83160. case BABYLON.PhysicsImpostor.BoxImpostor:
  83161. var box = extendSize.scale(0.5);
  83162. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83163. break;
  83164. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83165. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83166. returnValue = new this.BJSCANNON.Plane();
  83167. break;
  83168. case BABYLON.PhysicsImpostor.MeshImpostor:
  83169. // should transform the vertex data to world coordinates!!
  83170. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83171. var rawFaces = object.getIndices ? object.getIndices() : [];
  83172. if (!rawVerts)
  83173. return;
  83174. // get only scale! so the object could transform correctly.
  83175. var oldPosition = object.position.clone();
  83176. var oldRotation = object.rotation && object.rotation.clone();
  83177. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83178. object.position.copyFromFloats(0, 0, 0);
  83179. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83180. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83181. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83182. var transform = object.computeWorldMatrix(true);
  83183. // convert rawVerts to object space
  83184. var temp = new Array();
  83185. var index;
  83186. for (index = 0; index < rawVerts.length; index += 3) {
  83187. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83188. }
  83189. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83190. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83191. //now set back the transformation!
  83192. object.position.copyFrom(oldPosition);
  83193. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83194. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83195. break;
  83196. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83197. var oldPosition2 = object.position.clone();
  83198. var oldRotation2 = object.rotation && object.rotation.clone();
  83199. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83200. object.position.copyFromFloats(0, 0, 0);
  83201. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83202. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83203. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83204. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83205. returnValue = this._createHeightmap(object);
  83206. object.position.copyFrom(oldPosition2);
  83207. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83208. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83209. object.computeWorldMatrix(true);
  83210. break;
  83211. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83212. returnValue = new this.BJSCANNON.Particle();
  83213. break;
  83214. }
  83215. return returnValue;
  83216. };
  83217. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83218. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83219. var transform = object.computeWorldMatrix(true);
  83220. // convert rawVerts to object space
  83221. var temp = new Array();
  83222. var index;
  83223. for (index = 0; index < pos.length; index += 3) {
  83224. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83225. }
  83226. pos = temp;
  83227. var matrix = new Array();
  83228. //For now pointDepth will not be used and will be automatically calculated.
  83229. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83230. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83231. var boundingInfo = object.getBoundingInfo();
  83232. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83233. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83234. var elementSize = dim * 2 / arraySize;
  83235. for (var i = 0; i < pos.length; i = i + 3) {
  83236. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83237. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83238. var y = -pos[i + 2] + minY;
  83239. if (!matrix[x]) {
  83240. matrix[x] = [];
  83241. }
  83242. if (!matrix[x][z]) {
  83243. matrix[x][z] = y;
  83244. }
  83245. matrix[x][z] = Math.max(y, matrix[x][z]);
  83246. }
  83247. for (var x = 0; x <= arraySize; ++x) {
  83248. if (!matrix[x]) {
  83249. var loc = 1;
  83250. while (!matrix[(x + loc) % arraySize]) {
  83251. loc++;
  83252. }
  83253. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83254. //console.log("missing x", x);
  83255. }
  83256. for (var z = 0; z <= arraySize; ++z) {
  83257. if (!matrix[x][z]) {
  83258. var loc = 1;
  83259. var newValue;
  83260. while (newValue === undefined) {
  83261. newValue = matrix[x][(z + loc++) % arraySize];
  83262. }
  83263. matrix[x][z] = newValue;
  83264. }
  83265. }
  83266. }
  83267. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83268. elementSize: elementSize
  83269. });
  83270. //For future reference, needed for body transformation
  83271. shape.minY = minY;
  83272. return shape;
  83273. };
  83274. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83275. var object = impostor.object;
  83276. //make sure it is updated...
  83277. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83278. // The delta between the mesh position and the mesh bounding box center
  83279. var bInfo = object.getBoundingInfo();
  83280. if (!bInfo)
  83281. return;
  83282. var center = impostor.getObjectCenter();
  83283. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83284. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83285. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83286. this._tmpPosition.copyFrom(center);
  83287. var quaternion = object.rotationQuaternion;
  83288. if (!quaternion) {
  83289. return;
  83290. }
  83291. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83292. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83293. //-90 DEG in X, precalculated
  83294. quaternion = quaternion.multiply(this._minus90X);
  83295. //Invert! (Precalculated, 90 deg in X)
  83296. //No need to clone. this will never change.
  83297. impostor.setDeltaRotation(this._plus90X);
  83298. }
  83299. //If it is a heightfield, if should be centered.
  83300. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83301. var mesh = object;
  83302. var boundingInfo = mesh.getBoundingInfo();
  83303. //calculate the correct body position:
  83304. var rotationQuaternion = mesh.rotationQuaternion;
  83305. mesh.rotationQuaternion = this._tmpUnityRotation;
  83306. mesh.computeWorldMatrix(true);
  83307. //get original center with no rotation
  83308. var c = center.clone();
  83309. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83310. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83311. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83312. mesh.setPreTransformMatrix(p);
  83313. mesh.computeWorldMatrix(true);
  83314. //calculate the translation
  83315. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83316. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83317. //add it inverted to the delta
  83318. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83319. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83320. //rotation is back
  83321. mesh.rotationQuaternion = rotationQuaternion;
  83322. mesh.setPreTransformMatrix(oldPivot);
  83323. mesh.computeWorldMatrix(true);
  83324. }
  83325. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83326. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83327. //this._tmpPosition.copyFrom(object.position);
  83328. }
  83329. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83330. //Now update the impostor object
  83331. impostor.physicsBody.position.copy(this._tmpPosition);
  83332. impostor.physicsBody.quaternion.copy(quaternion);
  83333. };
  83334. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83335. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83336. if (impostor.object.rotationQuaternion) {
  83337. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83338. }
  83339. };
  83340. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83341. impostor.physicsBody.position.copy(newPosition);
  83342. impostor.physicsBody.quaternion.copy(newRotation);
  83343. };
  83344. CannonJSPlugin.prototype.isSupported = function () {
  83345. return this.BJSCANNON !== undefined;
  83346. };
  83347. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83348. impostor.physicsBody.velocity.copy(velocity);
  83349. };
  83350. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83351. impostor.physicsBody.angularVelocity.copy(velocity);
  83352. };
  83353. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83354. var v = impostor.physicsBody.velocity;
  83355. if (!v) {
  83356. return null;
  83357. }
  83358. return new BABYLON.Vector3(v.x, v.y, v.z);
  83359. };
  83360. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83361. var v = impostor.physicsBody.angularVelocity;
  83362. if (!v) {
  83363. return null;
  83364. }
  83365. return new BABYLON.Vector3(v.x, v.y, v.z);
  83366. };
  83367. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83368. impostor.physicsBody.mass = mass;
  83369. impostor.physicsBody.updateMassProperties();
  83370. };
  83371. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83372. return impostor.physicsBody.mass;
  83373. };
  83374. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83375. return impostor.physicsBody.material.friction;
  83376. };
  83377. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83378. impostor.physicsBody.material.friction = friction;
  83379. };
  83380. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83381. return impostor.physicsBody.material.restitution;
  83382. };
  83383. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83384. impostor.physicsBody.material.restitution = restitution;
  83385. };
  83386. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83387. impostor.physicsBody.sleep();
  83388. };
  83389. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83390. impostor.physicsBody.wakeUp();
  83391. };
  83392. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83393. joint.physicsJoint.distance = maxDistance;
  83394. };
  83395. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83396. // if (!motorIndex) {
  83397. // joint.physicsJoint.enableMotor();
  83398. // }
  83399. // }
  83400. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83401. // if (!motorIndex) {
  83402. // joint.physicsJoint.disableMotor();
  83403. // }
  83404. // }
  83405. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83406. if (!motorIndex) {
  83407. joint.physicsJoint.enableMotor();
  83408. joint.physicsJoint.setMotorSpeed(speed);
  83409. if (maxForce) {
  83410. this.setLimit(joint, maxForce);
  83411. }
  83412. }
  83413. };
  83414. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83415. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83416. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83417. };
  83418. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83419. var body = impostor.physicsBody;
  83420. mesh.position.x = body.position.x;
  83421. mesh.position.y = body.position.y;
  83422. mesh.position.z = body.position.z;
  83423. if (mesh.rotationQuaternion) {
  83424. mesh.rotationQuaternion.x = body.quaternion.x;
  83425. mesh.rotationQuaternion.y = body.quaternion.y;
  83426. mesh.rotationQuaternion.z = body.quaternion.z;
  83427. mesh.rotationQuaternion.w = body.quaternion.w;
  83428. }
  83429. };
  83430. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83431. var shape = impostor.physicsBody.shapes[0];
  83432. return shape.boundingSphereRadius;
  83433. };
  83434. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83435. var shape = impostor.physicsBody.shapes[0];
  83436. result.x = shape.halfExtents.x * 2;
  83437. result.y = shape.halfExtents.y * 2;
  83438. result.z = shape.halfExtents.z * 2;
  83439. };
  83440. CannonJSPlugin.prototype.dispose = function () {
  83441. };
  83442. CannonJSPlugin.prototype._extendNamespace = function () {
  83443. //this will force cannon to execute at least one step when using interpolation
  83444. var step_tmp1 = new this.BJSCANNON.Vec3();
  83445. var Engine = this.BJSCANNON;
  83446. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83447. maxSubSteps = maxSubSteps || 10;
  83448. timeSinceLastCalled = timeSinceLastCalled || 0;
  83449. if (timeSinceLastCalled === 0) {
  83450. this.internalStep(dt);
  83451. this.time += dt;
  83452. }
  83453. else {
  83454. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83455. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83456. var t0 = performance.now();
  83457. for (var i = 0; i !== internalSteps; i++) {
  83458. this.internalStep(dt);
  83459. if (performance.now() - t0 > dt * 1000) {
  83460. break;
  83461. }
  83462. }
  83463. this.time += timeSinceLastCalled;
  83464. var h = this.time % dt;
  83465. var h_div_dt = h / dt;
  83466. var interpvelo = step_tmp1;
  83467. var bodies = this.bodies;
  83468. for (var j = 0; j !== bodies.length; j++) {
  83469. var b = bodies[j];
  83470. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83471. b.position.vsub(b.previousPosition, interpvelo);
  83472. interpvelo.scale(h_div_dt, interpvelo);
  83473. b.position.vadd(interpvelo, b.interpolatedPosition);
  83474. }
  83475. else {
  83476. b.interpolatedPosition.copy(b.position);
  83477. b.interpolatedQuaternion.copy(b.quaternion);
  83478. }
  83479. }
  83480. }
  83481. };
  83482. };
  83483. return CannonJSPlugin;
  83484. }());
  83485. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83486. })(BABYLON || (BABYLON = {}));
  83487. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83488. var BABYLON;
  83489. (function (BABYLON) {
  83490. var OimoJSPlugin = /** @class */ (function () {
  83491. function OimoJSPlugin(iterations) {
  83492. this.name = "OimoJSPlugin";
  83493. this._tmpImpostorsArray = [];
  83494. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83495. this.BJSOIMO = OIMO;
  83496. this.world = new this.BJSOIMO.World({
  83497. iterations: iterations
  83498. });
  83499. this.world.clear();
  83500. }
  83501. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83502. this.world.gravity.copy(gravity);
  83503. };
  83504. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83505. this.world.timeStep = timeStep;
  83506. };
  83507. OimoJSPlugin.prototype.getTimeStep = function () {
  83508. return this.world.timeStep;
  83509. };
  83510. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83511. var _this = this;
  83512. impostors.forEach(function (impostor) {
  83513. impostor.beforeStep();
  83514. });
  83515. this.world.step();
  83516. impostors.forEach(function (impostor) {
  83517. impostor.afterStep();
  83518. //update the ordered impostors array
  83519. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83520. });
  83521. //check for collisions
  83522. var contact = this.world.contacts;
  83523. while (contact !== null) {
  83524. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83525. contact = contact.next;
  83526. continue;
  83527. }
  83528. //is this body colliding with any other? get the impostor
  83529. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83530. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83531. if (!mainImpostor || !collidingImpostor) {
  83532. contact = contact.next;
  83533. continue;
  83534. }
  83535. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83536. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83537. contact = contact.next;
  83538. }
  83539. };
  83540. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83541. var mass = impostor.physicsBody.mass;
  83542. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83543. };
  83544. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83545. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83546. this.applyImpulse(impostor, force, contactPoint);
  83547. };
  83548. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83549. var _this = this;
  83550. //parent-child relationship. Does this impostor has a parent impostor?
  83551. if (impostor.parent) {
  83552. if (impostor.physicsBody) {
  83553. this.removePhysicsBody(impostor);
  83554. //TODO is that needed?
  83555. impostor.forceUpdate();
  83556. }
  83557. return;
  83558. }
  83559. if (impostor.isBodyInitRequired()) {
  83560. var bodyConfig = {
  83561. name: impostor.uniqueId,
  83562. //Oimo must have mass, also for static objects.
  83563. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83564. size: [],
  83565. type: [],
  83566. pos: [],
  83567. posShape: [],
  83568. rot: [],
  83569. rotShape: [],
  83570. move: impostor.getParam("mass") !== 0,
  83571. density: impostor.getParam("mass"),
  83572. friction: impostor.getParam("friction"),
  83573. restitution: impostor.getParam("restitution"),
  83574. //Supporting older versions of Oimo
  83575. world: this.world
  83576. };
  83577. var impostors = [impostor];
  83578. var addToArray = function (parent) {
  83579. if (!parent.getChildMeshes)
  83580. return;
  83581. parent.getChildMeshes().forEach(function (m) {
  83582. if (m.physicsImpostor) {
  83583. impostors.push(m.physicsImpostor);
  83584. //m.physicsImpostor._init();
  83585. }
  83586. });
  83587. };
  83588. addToArray(impostor.object);
  83589. var checkWithEpsilon_1 = function (value) {
  83590. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83591. };
  83592. impostors.forEach(function (i) {
  83593. if (!i.object.rotationQuaternion) {
  83594. return;
  83595. }
  83596. //get the correct bounding box
  83597. var oldQuaternion = i.object.rotationQuaternion;
  83598. var rot = oldQuaternion.toEulerAngles();
  83599. var extendSize = i.getObjectExtendSize();
  83600. var radToDeg = 57.295779513082320876;
  83601. if (i === impostor) {
  83602. var center = impostor.getObjectCenter();
  83603. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83604. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83605. //Can also use Array.prototype.push.apply
  83606. bodyConfig.pos.push(center.x);
  83607. bodyConfig.pos.push(center.y);
  83608. bodyConfig.pos.push(center.z);
  83609. bodyConfig.posShape.push(0, 0, 0);
  83610. //tmp solution
  83611. bodyConfig.rot.push(rot.x * radToDeg);
  83612. bodyConfig.rot.push(rot.y * radToDeg);
  83613. bodyConfig.rot.push(rot.z * radToDeg);
  83614. bodyConfig.rotShape.push(0, 0, 0);
  83615. }
  83616. else {
  83617. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83618. bodyConfig.posShape.push(localPosition.x);
  83619. bodyConfig.posShape.push(localPosition.y);
  83620. bodyConfig.posShape.push(localPosition.z);
  83621. bodyConfig.pos.push(0, 0, 0);
  83622. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83623. bodyConfig.rot.push(0);
  83624. bodyConfig.rot.push(0);
  83625. bodyConfig.rot.push(0);
  83626. bodyConfig.rotShape.push(rot.x * radToDeg);
  83627. bodyConfig.rotShape.push(rot.y * radToDeg);
  83628. bodyConfig.rotShape.push(rot.z * radToDeg);
  83629. }
  83630. // register mesh
  83631. switch (i.type) {
  83632. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83633. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83634. case BABYLON.PhysicsImpostor.SphereImpostor:
  83635. var radiusX = extendSize.x;
  83636. var radiusY = extendSize.y;
  83637. var radiusZ = extendSize.z;
  83638. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83639. bodyConfig.type.push('sphere');
  83640. //due to the way oimo works with compounds, add 3 times
  83641. bodyConfig.size.push(size);
  83642. bodyConfig.size.push(size);
  83643. bodyConfig.size.push(size);
  83644. break;
  83645. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83646. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83647. var sizeY = checkWithEpsilon_1(extendSize.y);
  83648. bodyConfig.type.push('cylinder');
  83649. bodyConfig.size.push(sizeX);
  83650. bodyConfig.size.push(sizeY);
  83651. //due to the way oimo works with compounds, add one more value.
  83652. bodyConfig.size.push(sizeY);
  83653. break;
  83654. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83655. case BABYLON.PhysicsImpostor.BoxImpostor:
  83656. default:
  83657. var sizeX = checkWithEpsilon_1(extendSize.x);
  83658. var sizeY = checkWithEpsilon_1(extendSize.y);
  83659. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83660. bodyConfig.type.push('box');
  83661. //if (i === impostor) {
  83662. bodyConfig.size.push(sizeX);
  83663. bodyConfig.size.push(sizeY);
  83664. bodyConfig.size.push(sizeZ);
  83665. //} else {
  83666. // bodyConfig.size.push(0,0,0);
  83667. //}
  83668. break;
  83669. }
  83670. //actually not needed, but hey...
  83671. i.object.rotationQuaternion = oldQuaternion;
  83672. });
  83673. impostor.physicsBody = this.world.add(bodyConfig);
  83674. }
  83675. else {
  83676. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83677. }
  83678. impostor.setDeltaPosition(this._tmpPositionVector);
  83679. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83680. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83681. };
  83682. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83683. //impostor.physicsBody.dispose();
  83684. //Same as : (older oimo versions)
  83685. this.world.removeRigidBody(impostor.physicsBody);
  83686. };
  83687. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83688. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83689. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83690. if (!mainBody || !connectedBody) {
  83691. return;
  83692. }
  83693. var jointData = impostorJoint.joint.jointData;
  83694. var options = jointData.nativeParams || {};
  83695. var type;
  83696. var nativeJointData = {
  83697. body1: mainBody,
  83698. body2: connectedBody,
  83699. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83700. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83701. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83702. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83703. min: options.min,
  83704. max: options.max,
  83705. collision: options.collision || jointData.collision,
  83706. spring: options.spring,
  83707. //supporting older version of Oimo
  83708. world: this.world
  83709. };
  83710. switch (impostorJoint.joint.type) {
  83711. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83712. type = "jointBall";
  83713. break;
  83714. case BABYLON.PhysicsJoint.SpringJoint:
  83715. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83716. var springData = jointData;
  83717. nativeJointData.min = springData.length || nativeJointData.min;
  83718. //Max should also be set, just make sure it is at least min
  83719. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83720. case BABYLON.PhysicsJoint.DistanceJoint:
  83721. type = "jointDistance";
  83722. nativeJointData.max = jointData.maxDistance;
  83723. break;
  83724. case BABYLON.PhysicsJoint.PrismaticJoint:
  83725. type = "jointPrisme";
  83726. break;
  83727. case BABYLON.PhysicsJoint.SliderJoint:
  83728. type = "jointSlide";
  83729. break;
  83730. case BABYLON.PhysicsJoint.WheelJoint:
  83731. type = "jointWheel";
  83732. break;
  83733. case BABYLON.PhysicsJoint.HingeJoint:
  83734. default:
  83735. type = "jointHinge";
  83736. break;
  83737. }
  83738. nativeJointData.type = type;
  83739. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83740. };
  83741. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83742. //Bug in Oimo prevents us from disposing a joint in the playground
  83743. //joint.joint.physicsJoint.dispose();
  83744. //So we will bruteforce it!
  83745. try {
  83746. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83747. }
  83748. catch (e) {
  83749. BABYLON.Tools.Warn(e);
  83750. }
  83751. };
  83752. OimoJSPlugin.prototype.isSupported = function () {
  83753. return this.BJSOIMO !== undefined;
  83754. };
  83755. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83756. if (!impostor.physicsBody.sleeping) {
  83757. //TODO check that
  83758. /*if (impostor.physicsBody.shapes.next) {
  83759. var parentShape = this._getLastShape(impostor.physicsBody);
  83760. impostor.object.position.copyFrom(parentShape.position);
  83761. console.log(parentShape.position);
  83762. } else {*/
  83763. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83764. //}
  83765. if (impostor.object.rotationQuaternion) {
  83766. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83767. }
  83768. }
  83769. };
  83770. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83771. var body = impostor.physicsBody;
  83772. body.position.copy(newPosition);
  83773. body.orientation.copy(newRotation);
  83774. body.syncShapes();
  83775. body.awake();
  83776. };
  83777. /*private _getLastShape(body: any): any {
  83778. var lastShape = body.shapes;
  83779. while (lastShape.next) {
  83780. lastShape = lastShape.next;
  83781. }
  83782. return lastShape;
  83783. }*/
  83784. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83785. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83786. };
  83787. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83788. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83789. };
  83790. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83791. var v = impostor.physicsBody.linearVelocity;
  83792. if (!v) {
  83793. return null;
  83794. }
  83795. return new BABYLON.Vector3(v.x, v.y, v.z);
  83796. };
  83797. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83798. var v = impostor.physicsBody.angularVelocity;
  83799. if (!v) {
  83800. return null;
  83801. }
  83802. return new BABYLON.Vector3(v.x, v.y, v.z);
  83803. };
  83804. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83805. var staticBody = mass === 0;
  83806. //this will actually set the body's density and not its mass.
  83807. //But this is how oimo treats the mass variable.
  83808. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83809. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83810. };
  83811. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83812. return impostor.physicsBody.shapes.density;
  83813. };
  83814. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83815. return impostor.physicsBody.shapes.friction;
  83816. };
  83817. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83818. impostor.physicsBody.shapes.friction = friction;
  83819. };
  83820. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83821. return impostor.physicsBody.shapes.restitution;
  83822. };
  83823. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83824. impostor.physicsBody.shapes.restitution = restitution;
  83825. };
  83826. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83827. impostor.physicsBody.sleep();
  83828. };
  83829. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83830. impostor.physicsBody.awake();
  83831. };
  83832. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83833. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83834. if (minDistance !== void 0) {
  83835. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83836. }
  83837. };
  83838. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83839. //TODO separate rotational and transational motors.
  83840. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83841. if (motor) {
  83842. motor.setMotor(speed, maxForce);
  83843. }
  83844. };
  83845. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83846. //TODO separate rotational and transational motors.
  83847. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83848. if (motor) {
  83849. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83850. }
  83851. };
  83852. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83853. var body = impostor.physicsBody;
  83854. mesh.position.x = body.position.x;
  83855. mesh.position.y = body.position.y;
  83856. mesh.position.z = body.position.z;
  83857. if (mesh.rotationQuaternion) {
  83858. mesh.rotationQuaternion.x = body.orientation.x;
  83859. mesh.rotationQuaternion.y = body.orientation.y;
  83860. mesh.rotationQuaternion.z = body.orientation.z;
  83861. mesh.rotationQuaternion.w = body.orientation.s;
  83862. }
  83863. };
  83864. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83865. return impostor.physicsBody.shapes.radius;
  83866. };
  83867. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83868. var shape = impostor.physicsBody.shapes;
  83869. result.x = shape.halfWidth * 2;
  83870. result.y = shape.halfHeight * 2;
  83871. result.z = shape.halfDepth * 2;
  83872. };
  83873. OimoJSPlugin.prototype.dispose = function () {
  83874. this.world.clear();
  83875. };
  83876. return OimoJSPlugin;
  83877. }());
  83878. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83879. })(BABYLON || (BABYLON = {}));
  83880. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83881. var BABYLON;
  83882. (function (BABYLON) {
  83883. /*
  83884. * Based on jsTGALoader - Javascript loader for TGA file
  83885. * By Vincent Thibault
  83886. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83887. */
  83888. var TGATools = /** @class */ (function () {
  83889. function TGATools() {
  83890. }
  83891. TGATools.GetTGAHeader = function (data) {
  83892. var offset = 0;
  83893. var header = {
  83894. id_length: data[offset++],
  83895. colormap_type: data[offset++],
  83896. image_type: data[offset++],
  83897. colormap_index: data[offset++] | data[offset++] << 8,
  83898. colormap_length: data[offset++] | data[offset++] << 8,
  83899. colormap_size: data[offset++],
  83900. origin: [
  83901. data[offset++] | data[offset++] << 8,
  83902. data[offset++] | data[offset++] << 8
  83903. ],
  83904. width: data[offset++] | data[offset++] << 8,
  83905. height: data[offset++] | data[offset++] << 8,
  83906. pixel_size: data[offset++],
  83907. flags: data[offset++]
  83908. };
  83909. return header;
  83910. };
  83911. TGATools.UploadContent = function (gl, data) {
  83912. // Not enough data to contain header ?
  83913. if (data.length < 19) {
  83914. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83915. return;
  83916. }
  83917. // Read Header
  83918. var offset = 18;
  83919. var header = TGATools.GetTGAHeader(data);
  83920. // Assume it's a valid Targa file.
  83921. if (header.id_length + offset > data.length) {
  83922. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83923. return;
  83924. }
  83925. // Skip not needed data
  83926. offset += header.id_length;
  83927. var use_rle = false;
  83928. var use_pal = false;
  83929. var use_grey = false;
  83930. // Get some informations.
  83931. switch (header.image_type) {
  83932. case TGATools._TYPE_RLE_INDEXED:
  83933. use_rle = true;
  83934. case TGATools._TYPE_INDEXED:
  83935. use_pal = true;
  83936. break;
  83937. case TGATools._TYPE_RLE_RGB:
  83938. use_rle = true;
  83939. case TGATools._TYPE_RGB:
  83940. // use_rgb = true;
  83941. break;
  83942. case TGATools._TYPE_RLE_GREY:
  83943. use_rle = true;
  83944. case TGATools._TYPE_GREY:
  83945. use_grey = true;
  83946. break;
  83947. }
  83948. var pixel_data;
  83949. // var numAlphaBits = header.flags & 0xf;
  83950. var pixel_size = header.pixel_size >> 3;
  83951. var pixel_total = header.width * header.height * pixel_size;
  83952. // Read palettes
  83953. var palettes;
  83954. if (use_pal) {
  83955. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83956. }
  83957. // Read LRE
  83958. if (use_rle) {
  83959. pixel_data = new Uint8Array(pixel_total);
  83960. var c, count, i;
  83961. var localOffset = 0;
  83962. var pixels = new Uint8Array(pixel_size);
  83963. while (offset < pixel_total && localOffset < pixel_total) {
  83964. c = data[offset++];
  83965. count = (c & 0x7f) + 1;
  83966. // RLE pixels
  83967. if (c & 0x80) {
  83968. // Bind pixel tmp array
  83969. for (i = 0; i < pixel_size; ++i) {
  83970. pixels[i] = data[offset++];
  83971. }
  83972. // Copy pixel array
  83973. for (i = 0; i < count; ++i) {
  83974. pixel_data.set(pixels, localOffset + i * pixel_size);
  83975. }
  83976. localOffset += pixel_size * count;
  83977. }
  83978. // Raw pixels
  83979. else {
  83980. count *= pixel_size;
  83981. for (i = 0; i < count; ++i) {
  83982. pixel_data[localOffset + i] = data[offset++];
  83983. }
  83984. localOffset += count;
  83985. }
  83986. }
  83987. }
  83988. // RAW Pixels
  83989. else {
  83990. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83991. }
  83992. // Load to texture
  83993. var x_start, y_start, x_step, y_step, y_end, x_end;
  83994. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83995. default:
  83996. case TGATools._ORIGIN_UL:
  83997. x_start = 0;
  83998. x_step = 1;
  83999. x_end = header.width;
  84000. y_start = 0;
  84001. y_step = 1;
  84002. y_end = header.height;
  84003. break;
  84004. case TGATools._ORIGIN_BL:
  84005. x_start = 0;
  84006. x_step = 1;
  84007. x_end = header.width;
  84008. y_start = header.height - 1;
  84009. y_step = -1;
  84010. y_end = -1;
  84011. break;
  84012. case TGATools._ORIGIN_UR:
  84013. x_start = header.width - 1;
  84014. x_step = -1;
  84015. x_end = -1;
  84016. y_start = 0;
  84017. y_step = 1;
  84018. y_end = header.height;
  84019. break;
  84020. case TGATools._ORIGIN_BR:
  84021. x_start = header.width - 1;
  84022. x_step = -1;
  84023. x_end = -1;
  84024. y_start = header.height - 1;
  84025. y_step = -1;
  84026. y_end = -1;
  84027. break;
  84028. }
  84029. // Load the specify method
  84030. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84031. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84032. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84033. };
  84034. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84035. var image = pixel_data, colormap = palettes;
  84036. var width = header.width, height = header.height;
  84037. var color, i = 0, x, y;
  84038. var imageData = new Uint8Array(width * height * 4);
  84039. for (y = y_start; y !== y_end; y += y_step) {
  84040. for (x = x_start; x !== x_end; x += x_step, i++) {
  84041. color = image[i];
  84042. imageData[(x + width * y) * 4 + 3] = 255;
  84043. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84044. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84045. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84046. }
  84047. }
  84048. return imageData;
  84049. };
  84050. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84051. var image = pixel_data;
  84052. var width = header.width, height = header.height;
  84053. var color, i = 0, x, y;
  84054. var imageData = new Uint8Array(width * height * 4);
  84055. for (y = y_start; y !== y_end; y += y_step) {
  84056. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84057. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84058. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84059. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84060. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84061. imageData[(x + width * y) * 4 + 0] = r;
  84062. imageData[(x + width * y) * 4 + 1] = g;
  84063. imageData[(x + width * y) * 4 + 2] = b;
  84064. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84065. }
  84066. }
  84067. return imageData;
  84068. };
  84069. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84070. var image = pixel_data;
  84071. var width = header.width, height = header.height;
  84072. var i = 0, x, y;
  84073. var imageData = new Uint8Array(width * height * 4);
  84074. for (y = y_start; y !== y_end; y += y_step) {
  84075. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84076. imageData[(x + width * y) * 4 + 3] = 255;
  84077. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84078. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84079. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84080. }
  84081. }
  84082. return imageData;
  84083. };
  84084. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84085. var image = pixel_data;
  84086. var width = header.width, height = header.height;
  84087. var i = 0, x, y;
  84088. var imageData = new Uint8Array(width * height * 4);
  84089. for (y = y_start; y !== y_end; y += y_step) {
  84090. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84091. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84092. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84093. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84094. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84095. }
  84096. }
  84097. return imageData;
  84098. };
  84099. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84100. var image = pixel_data;
  84101. var width = header.width, height = header.height;
  84102. var color, i = 0, x, y;
  84103. var imageData = new Uint8Array(width * height * 4);
  84104. for (y = y_start; y !== y_end; y += y_step) {
  84105. for (x = x_start; x !== x_end; x += x_step, i++) {
  84106. color = image[i];
  84107. imageData[(x + width * y) * 4 + 0] = color;
  84108. imageData[(x + width * y) * 4 + 1] = color;
  84109. imageData[(x + width * y) * 4 + 2] = color;
  84110. imageData[(x + width * y) * 4 + 3] = 255;
  84111. }
  84112. }
  84113. return imageData;
  84114. };
  84115. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84116. var image = pixel_data;
  84117. var width = header.width, height = header.height;
  84118. var i = 0, x, y;
  84119. var imageData = new Uint8Array(width * height * 4);
  84120. for (y = y_start; y !== y_end; y += y_step) {
  84121. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84122. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84123. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84124. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84125. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84126. }
  84127. }
  84128. return imageData;
  84129. };
  84130. //private static _TYPE_NO_DATA = 0;
  84131. TGATools._TYPE_INDEXED = 1;
  84132. TGATools._TYPE_RGB = 2;
  84133. TGATools._TYPE_GREY = 3;
  84134. TGATools._TYPE_RLE_INDEXED = 9;
  84135. TGATools._TYPE_RLE_RGB = 10;
  84136. TGATools._TYPE_RLE_GREY = 11;
  84137. TGATools._ORIGIN_MASK = 0x30;
  84138. TGATools._ORIGIN_SHIFT = 0x04;
  84139. TGATools._ORIGIN_BL = 0x00;
  84140. TGATools._ORIGIN_BR = 0x01;
  84141. TGATools._ORIGIN_UL = 0x02;
  84142. TGATools._ORIGIN_UR = 0x03;
  84143. return TGATools;
  84144. }());
  84145. BABYLON.TGATools = TGATools;
  84146. })(BABYLON || (BABYLON = {}));
  84147. //# sourceMappingURL=babylon.tga.js.map
  84148. var BABYLON;
  84149. (function (BABYLON) {
  84150. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84151. // All values and structures referenced from:
  84152. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84153. var DDS_MAGIC = 0x20534444;
  84154. var
  84155. //DDSD_CAPS = 0x1,
  84156. //DDSD_HEIGHT = 0x2,
  84157. //DDSD_WIDTH = 0x4,
  84158. //DDSD_PITCH = 0x8,
  84159. //DDSD_PIXELFORMAT = 0x1000,
  84160. DDSD_MIPMAPCOUNT = 0x20000;
  84161. //DDSD_LINEARSIZE = 0x80000,
  84162. //DDSD_DEPTH = 0x800000;
  84163. // var DDSCAPS_COMPLEX = 0x8,
  84164. // DDSCAPS_MIPMAP = 0x400000,
  84165. // DDSCAPS_TEXTURE = 0x1000;
  84166. var DDSCAPS2_CUBEMAP = 0x200;
  84167. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84168. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84169. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84170. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84171. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84172. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84173. // DDSCAPS2_VOLUME = 0x200000;
  84174. var
  84175. //DDPF_ALPHAPIXELS = 0x1,
  84176. //DDPF_ALPHA = 0x2,
  84177. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84178. //DDPF_YUV = 0x200,
  84179. DDPF_LUMINANCE = 0x20000;
  84180. function FourCCToInt32(value) {
  84181. return value.charCodeAt(0) +
  84182. (value.charCodeAt(1) << 8) +
  84183. (value.charCodeAt(2) << 16) +
  84184. (value.charCodeAt(3) << 24);
  84185. }
  84186. function Int32ToFourCC(value) {
  84187. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84188. }
  84189. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84190. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84191. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84192. var FOURCC_DX10 = FourCCToInt32("DX10");
  84193. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84194. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84195. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84196. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84197. var headerLengthInt = 31; // The header length in 32 bit ints
  84198. // Offsets into the header array
  84199. var off_magic = 0;
  84200. var off_size = 1;
  84201. var off_flags = 2;
  84202. var off_height = 3;
  84203. var off_width = 4;
  84204. var off_mipmapCount = 7;
  84205. var off_pfFlags = 20;
  84206. var off_pfFourCC = 21;
  84207. var off_RGBbpp = 22;
  84208. var off_RMask = 23;
  84209. var off_GMask = 24;
  84210. var off_BMask = 25;
  84211. var off_AMask = 26;
  84212. // var off_caps1 = 27;
  84213. var off_caps2 = 28;
  84214. // var off_caps3 = 29;
  84215. // var off_caps4 = 30;
  84216. var off_dxgiFormat = 32;
  84217. ;
  84218. var DDSTools = /** @class */ (function () {
  84219. function DDSTools() {
  84220. }
  84221. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84222. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84223. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84224. var mipmapCount = 1;
  84225. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84226. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84227. }
  84228. var fourCC = header[off_pfFourCC];
  84229. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84230. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84231. switch (fourCC) {
  84232. case FOURCC_D3DFMT_R16G16B16A16F:
  84233. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84234. break;
  84235. case FOURCC_D3DFMT_R32G32B32A32F:
  84236. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84237. break;
  84238. case FOURCC_DX10:
  84239. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84240. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84241. break;
  84242. }
  84243. }
  84244. return {
  84245. width: header[off_width],
  84246. height: header[off_height],
  84247. mipmapCount: mipmapCount,
  84248. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84249. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84250. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84251. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84252. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84253. dxgiFormat: dxgiFormat,
  84254. textureType: textureType
  84255. };
  84256. };
  84257. DDSTools._ToHalfFloat = function (value) {
  84258. if (!DDSTools._FloatView) {
  84259. DDSTools._FloatView = new Float32Array(1);
  84260. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84261. }
  84262. DDSTools._FloatView[0] = value;
  84263. var x = DDSTools._Int32View[0];
  84264. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84265. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84266. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84267. /* If zero, or denormal, or exponent underflows too much for a denormal
  84268. * half, return signed zero. */
  84269. if (e < 103) {
  84270. return bits;
  84271. }
  84272. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84273. if (e > 142) {
  84274. bits |= 0x7c00;
  84275. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84276. * not Inf, so make sure we set one mantissa bit too. */
  84277. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84278. return bits;
  84279. }
  84280. /* If exponent underflows but not too much, return a denormal */
  84281. if (e < 113) {
  84282. m |= 0x0800;
  84283. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84284. * to 1, which is OK. */
  84285. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84286. return bits;
  84287. }
  84288. bits |= ((e - 112) << 10) | (m >> 1);
  84289. bits += m & 1;
  84290. return bits;
  84291. };
  84292. DDSTools._FromHalfFloat = function (value) {
  84293. var s = (value & 0x8000) >> 15;
  84294. var e = (value & 0x7C00) >> 10;
  84295. var f = value & 0x03FF;
  84296. if (e === 0) {
  84297. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84298. }
  84299. else if (e == 0x1F) {
  84300. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84301. }
  84302. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84303. };
  84304. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84305. var destArray = new Float32Array(dataLength);
  84306. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84307. var index = 0;
  84308. for (var y = 0; y < height; y++) {
  84309. for (var x = 0; x < width; x++) {
  84310. var srcPos = (x + y * width) * 4;
  84311. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84312. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84313. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84314. if (DDSTools.StoreLODInAlphaChannel) {
  84315. destArray[index + 3] = lod;
  84316. }
  84317. else {
  84318. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84319. }
  84320. index += 4;
  84321. }
  84322. }
  84323. return destArray;
  84324. };
  84325. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84326. if (DDSTools.StoreLODInAlphaChannel) {
  84327. var destArray = new Uint16Array(dataLength);
  84328. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84329. var index = 0;
  84330. for (var y = 0; y < height; y++) {
  84331. for (var x = 0; x < width; x++) {
  84332. var srcPos = (x + y * width) * 4;
  84333. destArray[index] = srcData[srcPos];
  84334. destArray[index + 1] = srcData[srcPos + 1];
  84335. destArray[index + 2] = srcData[srcPos + 2];
  84336. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84337. index += 4;
  84338. }
  84339. }
  84340. return destArray;
  84341. }
  84342. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84343. };
  84344. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84345. if (DDSTools.StoreLODInAlphaChannel) {
  84346. var destArray = new Float32Array(dataLength);
  84347. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84348. var index = 0;
  84349. for (var y = 0; y < height; y++) {
  84350. for (var x = 0; x < width; x++) {
  84351. var srcPos = (x + y * width) * 4;
  84352. destArray[index] = srcData[srcPos];
  84353. destArray[index + 1] = srcData[srcPos + 1];
  84354. destArray[index + 2] = srcData[srcPos + 2];
  84355. destArray[index + 3] = lod;
  84356. index += 4;
  84357. }
  84358. }
  84359. return destArray;
  84360. }
  84361. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84362. };
  84363. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84364. var destArray = new Uint8Array(dataLength);
  84365. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84366. var index = 0;
  84367. for (var y = 0; y < height; y++) {
  84368. for (var x = 0; x < width; x++) {
  84369. var srcPos = (x + y * width) * 4;
  84370. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84371. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84372. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84373. if (DDSTools.StoreLODInAlphaChannel) {
  84374. destArray[index + 3] = lod;
  84375. }
  84376. else {
  84377. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84378. }
  84379. index += 4;
  84380. }
  84381. }
  84382. return destArray;
  84383. };
  84384. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84385. var destArray = new Uint8Array(dataLength);
  84386. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84387. var index = 0;
  84388. for (var y = 0; y < height; y++) {
  84389. for (var x = 0; x < width; x++) {
  84390. var srcPos = (x + y * width) * 4;
  84391. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84392. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84393. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84394. if (DDSTools.StoreLODInAlphaChannel) {
  84395. destArray[index + 3] = lod;
  84396. }
  84397. else {
  84398. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84399. }
  84400. index += 4;
  84401. }
  84402. }
  84403. return destArray;
  84404. };
  84405. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84406. var byteArray = new Uint8Array(dataLength);
  84407. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84408. var index = 0;
  84409. for (var y = 0; y < height; y++) {
  84410. for (var x = 0; x < width; x++) {
  84411. var srcPos = (x + y * width) * 4;
  84412. byteArray[index] = srcData[srcPos + rOffset];
  84413. byteArray[index + 1] = srcData[srcPos + gOffset];
  84414. byteArray[index + 2] = srcData[srcPos + bOffset];
  84415. byteArray[index + 3] = srcData[srcPos + aOffset];
  84416. index += 4;
  84417. }
  84418. }
  84419. return byteArray;
  84420. };
  84421. DDSTools._ExtractLongWordOrder = function (value) {
  84422. if (value === 0 || value === 255 || value === -16777216) {
  84423. return 0;
  84424. }
  84425. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84426. };
  84427. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84428. var byteArray = new Uint8Array(dataLength);
  84429. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84430. var index = 0;
  84431. for (var y = 0; y < height; y++) {
  84432. for (var x = 0; x < width; x++) {
  84433. var srcPos = (x + y * width) * 3;
  84434. byteArray[index] = srcData[srcPos + rOffset];
  84435. byteArray[index + 1] = srcData[srcPos + gOffset];
  84436. byteArray[index + 2] = srcData[srcPos + bOffset];
  84437. index += 3;
  84438. }
  84439. }
  84440. return byteArray;
  84441. };
  84442. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84443. var byteArray = new Uint8Array(dataLength);
  84444. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84445. var index = 0;
  84446. for (var y = 0; y < height; y++) {
  84447. for (var x = 0; x < width; x++) {
  84448. var srcPos = (x + y * width);
  84449. byteArray[index] = srcData[srcPos];
  84450. index++;
  84451. }
  84452. }
  84453. return byteArray;
  84454. };
  84455. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84456. if (lodIndex === void 0) { lodIndex = -1; }
  84457. var sphericalPolynomialFaces = null;
  84458. if (info.sphericalPolynomial) {
  84459. sphericalPolynomialFaces = new Array();
  84460. }
  84461. var ext = engine.getCaps().s3tc;
  84462. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84463. var fourCC, width, height, dataLength = 0, dataOffset;
  84464. var byteArray, mipmapCount, mip;
  84465. var internalFormat = 0;
  84466. var format = 0;
  84467. var blockBytes = 1;
  84468. if (header[off_magic] !== DDS_MAGIC) {
  84469. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84470. return;
  84471. }
  84472. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84473. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84474. return;
  84475. }
  84476. if (info.isCompressed && !ext) {
  84477. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84478. return;
  84479. }
  84480. var bpp = header[off_RGBbpp];
  84481. dataOffset = header[off_size] + 4;
  84482. var computeFormats = false;
  84483. if (info.isFourCC) {
  84484. fourCC = header[off_pfFourCC];
  84485. switch (fourCC) {
  84486. case FOURCC_DXT1:
  84487. blockBytes = 8;
  84488. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84489. break;
  84490. case FOURCC_DXT3:
  84491. blockBytes = 16;
  84492. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84493. break;
  84494. case FOURCC_DXT5:
  84495. blockBytes = 16;
  84496. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84497. break;
  84498. case FOURCC_D3DFMT_R16G16B16A16F:
  84499. computeFormats = true;
  84500. break;
  84501. case FOURCC_D3DFMT_R32G32B32A32F:
  84502. computeFormats = true;
  84503. break;
  84504. case FOURCC_DX10:
  84505. // There is an additionnal header so dataOffset need to be changed
  84506. dataOffset += 5 * 4; // 5 uints
  84507. var supported = false;
  84508. switch (info.dxgiFormat) {
  84509. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84510. computeFormats = true;
  84511. supported = true;
  84512. break;
  84513. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84514. info.isRGB = true;
  84515. info.isFourCC = false;
  84516. bpp = 32;
  84517. supported = true;
  84518. break;
  84519. }
  84520. if (supported) {
  84521. break;
  84522. }
  84523. default:
  84524. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84525. return;
  84526. }
  84527. }
  84528. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84529. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84530. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84531. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84532. if (computeFormats) {
  84533. format = engine._getWebGLTextureType(info.textureType);
  84534. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84535. }
  84536. mipmapCount = 1;
  84537. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84538. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84539. }
  84540. for (var face = 0; face < faces; face++) {
  84541. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84542. width = header[off_width];
  84543. height = header[off_height];
  84544. for (mip = 0; mip < mipmapCount; ++mip) {
  84545. if (lodIndex === -1 || lodIndex === mip) {
  84546. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84547. var i = (lodIndex === -1) ? mip : 0;
  84548. if (!info.isCompressed && info.isFourCC) {
  84549. dataLength = width * height * 4;
  84550. var floatArray = null;
  84551. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84552. if (bpp === 128) {
  84553. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84554. if (sphericalPolynomialFaces && i == 0) {
  84555. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84556. }
  84557. }
  84558. else if (bpp === 64) {
  84559. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84560. if (sphericalPolynomialFaces && i == 0) {
  84561. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84562. }
  84563. }
  84564. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84565. format = engine._getWebGLTextureType(info.textureType);
  84566. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84567. }
  84568. else {
  84569. if (bpp === 128) {
  84570. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84571. if (sphericalPolynomialFaces && i == 0) {
  84572. sphericalPolynomialFaces.push(floatArray);
  84573. }
  84574. }
  84575. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84576. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84577. if (sphericalPolynomialFaces && i == 0) {
  84578. sphericalPolynomialFaces.push(floatArray);
  84579. }
  84580. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84581. format = engine._getWebGLTextureType(info.textureType);
  84582. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84583. }
  84584. else { // 64
  84585. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84586. if (sphericalPolynomialFaces && i == 0) {
  84587. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84588. }
  84589. }
  84590. }
  84591. if (floatArray) {
  84592. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84593. }
  84594. }
  84595. else if (info.isRGB) {
  84596. if (bpp === 24) {
  84597. dataLength = width * height * 3;
  84598. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84599. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84600. }
  84601. else { // 32
  84602. dataLength = width * height * 4;
  84603. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84604. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84605. }
  84606. }
  84607. else if (info.isLuminance) {
  84608. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84609. var unpaddedRowSize = width;
  84610. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84611. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84612. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84613. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84614. }
  84615. else {
  84616. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84617. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84618. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84619. }
  84620. }
  84621. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84622. width *= 0.5;
  84623. height *= 0.5;
  84624. width = Math.max(1.0, width);
  84625. height = Math.max(1.0, height);
  84626. }
  84627. if (currentFace !== undefined) {
  84628. // Loading a single face
  84629. break;
  84630. }
  84631. }
  84632. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84633. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84634. size: header[off_width],
  84635. right: sphericalPolynomialFaces[0],
  84636. left: sphericalPolynomialFaces[1],
  84637. up: sphericalPolynomialFaces[2],
  84638. down: sphericalPolynomialFaces[3],
  84639. front: sphericalPolynomialFaces[4],
  84640. back: sphericalPolynomialFaces[5],
  84641. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84642. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84643. gammaSpace: false,
  84644. });
  84645. }
  84646. else {
  84647. info.sphericalPolynomial = undefined;
  84648. }
  84649. };
  84650. DDSTools.StoreLODInAlphaChannel = false;
  84651. return DDSTools;
  84652. }());
  84653. BABYLON.DDSTools = DDSTools;
  84654. })(BABYLON || (BABYLON = {}));
  84655. //# sourceMappingURL=babylon.dds.js.map
  84656. var BABYLON;
  84657. (function (BABYLON) {
  84658. /**
  84659. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84660. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84661. */
  84662. var KhronosTextureContainer = /** @class */ (function () {
  84663. /**
  84664. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84665. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84666. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84667. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84668. */
  84669. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84670. this.arrayBuffer = arrayBuffer;
  84671. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84672. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84673. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84674. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84675. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84676. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84677. BABYLON.Tools.Error("texture missing KTX identifier");
  84678. return;
  84679. }
  84680. // load the reset of the header in native 32 bit int
  84681. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84682. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84683. var oppositeEndianess = header[0] === 0x01020304;
  84684. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84685. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84686. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84687. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84688. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84689. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84690. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84691. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84692. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84693. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84694. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84695. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84696. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84697. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84698. if (this.glType !== 0) {
  84699. BABYLON.Tools.Error("only compressed formats currently supported");
  84700. return;
  84701. }
  84702. else {
  84703. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84704. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84705. }
  84706. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84707. BABYLON.Tools.Error("only 2D textures currently supported");
  84708. return;
  84709. }
  84710. if (this.numberOfArrayElements !== 0) {
  84711. BABYLON.Tools.Error("texture arrays not currently supported");
  84712. return;
  84713. }
  84714. if (this.numberOfFaces !== facesExpected) {
  84715. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84716. return;
  84717. }
  84718. // we now have a completely validated file, so could use existence of loadType as success
  84719. // would need to make this more elaborate & adjust checks above to support more than one load type
  84720. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84721. }
  84722. // not as fast hardware based, but will probably never need to use
  84723. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84724. return ((val & 0xFF) << 24)
  84725. | ((val & 0xFF00) << 8)
  84726. | ((val >> 8) & 0xFF00)
  84727. | ((val >> 24) & 0xFF);
  84728. };
  84729. /**
  84730. * It is assumed that the texture has already been created & is currently bound
  84731. */
  84732. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84733. switch (this.loadType) {
  84734. case KhronosTextureContainer.COMPRESSED_2D:
  84735. this._upload2DCompressedLevels(gl, loadMipmaps);
  84736. break;
  84737. case KhronosTextureContainer.TEX_2D:
  84738. case KhronosTextureContainer.COMPRESSED_3D:
  84739. case KhronosTextureContainer.TEX_3D:
  84740. }
  84741. };
  84742. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84743. // initialize width & height for level 1
  84744. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84745. var width = this.pixelWidth;
  84746. var height = this.pixelHeight;
  84747. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84748. for (var level = 0; level < mipmapCount; level++) {
  84749. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84750. for (var face = 0; face < this.numberOfFaces; face++) {
  84751. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84752. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84753. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84754. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84755. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84756. }
  84757. width = Math.max(1.0, width * 0.5);
  84758. height = Math.max(1.0, height * 0.5);
  84759. }
  84760. };
  84761. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84762. // load types
  84763. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84764. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84765. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84766. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84767. return KhronosTextureContainer;
  84768. }());
  84769. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84770. })(BABYLON || (BABYLON = {}));
  84771. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84772. var BABYLON;
  84773. (function (BABYLON) {
  84774. var Debug;
  84775. (function (Debug) {
  84776. /**
  84777. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84778. */
  84779. var SkeletonViewer = /** @class */ (function () {
  84780. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84781. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84782. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84783. this.skeleton = skeleton;
  84784. this.mesh = mesh;
  84785. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84786. this.renderingGroupId = renderingGroupId;
  84787. this.color = BABYLON.Color3.White();
  84788. this._debugLines = new Array();
  84789. this._isEnabled = false;
  84790. this._scene = scene;
  84791. this.update();
  84792. this._renderFunction = this.update.bind(this);
  84793. }
  84794. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84795. get: function () {
  84796. return this._isEnabled;
  84797. },
  84798. set: function (value) {
  84799. if (this._isEnabled === value) {
  84800. return;
  84801. }
  84802. this._isEnabled = value;
  84803. if (value) {
  84804. this._scene.registerBeforeRender(this._renderFunction);
  84805. }
  84806. else {
  84807. this._scene.unregisterBeforeRender(this._renderFunction);
  84808. }
  84809. },
  84810. enumerable: true,
  84811. configurable: true
  84812. });
  84813. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84814. if (x === void 0) { x = 0; }
  84815. if (y === void 0) { y = 0; }
  84816. if (z === void 0) { z = 0; }
  84817. var tmat = BABYLON.Tmp.Matrix[0];
  84818. var parentBone = bone.getParent();
  84819. tmat.copyFrom(bone.getLocalMatrix());
  84820. if (x !== 0 || y !== 0 || z !== 0) {
  84821. var tmat2 = BABYLON.Tmp.Matrix[1];
  84822. BABYLON.Matrix.IdentityToRef(tmat2);
  84823. tmat2.m[12] = x;
  84824. tmat2.m[13] = y;
  84825. tmat2.m[14] = z;
  84826. tmat2.multiplyToRef(tmat, tmat);
  84827. }
  84828. if (parentBone) {
  84829. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84830. }
  84831. tmat.multiplyToRef(meshMat, tmat);
  84832. position.x = tmat.m[12];
  84833. position.y = tmat.m[13];
  84834. position.z = tmat.m[14];
  84835. };
  84836. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84837. var len = bones.length;
  84838. var meshPos = this.mesh.position;
  84839. for (var i = 0; i < len; i++) {
  84840. var bone = bones[i];
  84841. var points = this._debugLines[i];
  84842. if (!points) {
  84843. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84844. this._debugLines[i] = points;
  84845. }
  84846. this._getBonePosition(points[0], bone, meshMat);
  84847. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84848. points[0].subtractInPlace(meshPos);
  84849. points[1].subtractInPlace(meshPos);
  84850. }
  84851. };
  84852. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84853. var len = bones.length;
  84854. var boneNum = 0;
  84855. var meshPos = this.mesh.position;
  84856. for (var i = len - 1; i >= 0; i--) {
  84857. var childBone = bones[i];
  84858. var parentBone = childBone.getParent();
  84859. if (!parentBone) {
  84860. continue;
  84861. }
  84862. var points = this._debugLines[boneNum];
  84863. if (!points) {
  84864. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84865. this._debugLines[boneNum] = points;
  84866. }
  84867. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84868. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84869. points[0].subtractInPlace(meshPos);
  84870. points[1].subtractInPlace(meshPos);
  84871. boneNum++;
  84872. }
  84873. };
  84874. SkeletonViewer.prototype.update = function () {
  84875. if (this.autoUpdateBonesMatrices) {
  84876. this.skeleton.computeAbsoluteTransforms();
  84877. }
  84878. if (this.skeleton.bones[0].length === undefined) {
  84879. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84880. }
  84881. else {
  84882. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84883. }
  84884. if (!this._debugMesh) {
  84885. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84886. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84887. }
  84888. else {
  84889. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84890. }
  84891. this._debugMesh.position.copyFrom(this.mesh.position);
  84892. this._debugMesh.color = this.color;
  84893. };
  84894. SkeletonViewer.prototype.dispose = function () {
  84895. if (this._debugMesh) {
  84896. this.isEnabled = false;
  84897. this._debugMesh.dispose();
  84898. this._debugMesh = null;
  84899. }
  84900. };
  84901. return SkeletonViewer;
  84902. }());
  84903. Debug.SkeletonViewer = SkeletonViewer;
  84904. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84905. })(BABYLON || (BABYLON = {}));
  84906. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84907. /**
  84908. * Module Debug contains the (visual) components to debug a scene correctly
  84909. */
  84910. var BABYLON;
  84911. (function (BABYLON) {
  84912. var Debug;
  84913. (function (Debug) {
  84914. /**
  84915. * The Axes viewer will show 3 axes in a specific point in space
  84916. */
  84917. var AxesViewer = /** @class */ (function () {
  84918. function AxesViewer(scene, scaleLines) {
  84919. if (scaleLines === void 0) { scaleLines = 1; }
  84920. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84921. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84922. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84923. this.scaleLines = 1;
  84924. this.scaleLines = scaleLines;
  84925. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84926. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84927. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84928. this._xmesh.renderingGroupId = 2;
  84929. this._ymesh.renderingGroupId = 2;
  84930. this._zmesh.renderingGroupId = 2;
  84931. this._xmesh.material.checkReadyOnlyOnce = true;
  84932. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84933. this._ymesh.material.checkReadyOnlyOnce = true;
  84934. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84935. this._zmesh.material.checkReadyOnlyOnce = true;
  84936. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84937. this.scene = scene;
  84938. }
  84939. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84940. var scaleLines = this.scaleLines;
  84941. if (this._xmesh) {
  84942. this._xmesh.position.copyFrom(position);
  84943. }
  84944. if (this._ymesh) {
  84945. this._ymesh.position.copyFrom(position);
  84946. }
  84947. if (this._zmesh) {
  84948. this._zmesh.position.copyFrom(position);
  84949. }
  84950. var point2 = this._xline[1];
  84951. point2.x = xaxis.x * scaleLines;
  84952. point2.y = xaxis.y * scaleLines;
  84953. point2.z = xaxis.z * scaleLines;
  84954. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84955. point2 = this._yline[1];
  84956. point2.x = yaxis.x * scaleLines;
  84957. point2.y = yaxis.y * scaleLines;
  84958. point2.z = yaxis.z * scaleLines;
  84959. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84960. point2 = this._zline[1];
  84961. point2.x = zaxis.x * scaleLines;
  84962. point2.y = zaxis.y * scaleLines;
  84963. point2.z = zaxis.z * scaleLines;
  84964. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84965. };
  84966. AxesViewer.prototype.dispose = function () {
  84967. if (this._xmesh) {
  84968. this._xmesh.dispose();
  84969. }
  84970. if (this._ymesh) {
  84971. this._ymesh.dispose();
  84972. }
  84973. if (this._zmesh) {
  84974. this._zmesh.dispose();
  84975. }
  84976. this._xmesh = null;
  84977. this._ymesh = null;
  84978. this._zmesh = null;
  84979. this.scene = null;
  84980. };
  84981. return AxesViewer;
  84982. }());
  84983. Debug.AxesViewer = AxesViewer;
  84984. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84985. })(BABYLON || (BABYLON = {}));
  84986. //# sourceMappingURL=babylon.axesViewer.js.map
  84987. var BABYLON;
  84988. (function (BABYLON) {
  84989. var Debug;
  84990. (function (Debug) {
  84991. /**
  84992. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84993. */
  84994. var BoneAxesViewer = /** @class */ (function (_super) {
  84995. __extends(BoneAxesViewer, _super);
  84996. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84997. if (scaleLines === void 0) { scaleLines = 1; }
  84998. var _this = _super.call(this, scene, scaleLines) || this;
  84999. _this.pos = BABYLON.Vector3.Zero();
  85000. _this.xaxis = BABYLON.Vector3.Zero();
  85001. _this.yaxis = BABYLON.Vector3.Zero();
  85002. _this.zaxis = BABYLON.Vector3.Zero();
  85003. _this.mesh = mesh;
  85004. _this.bone = bone;
  85005. return _this;
  85006. }
  85007. BoneAxesViewer.prototype.update = function () {
  85008. if (!this.mesh || !this.bone) {
  85009. return;
  85010. }
  85011. var bone = this.bone;
  85012. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85013. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85014. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85015. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85016. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85017. };
  85018. BoneAxesViewer.prototype.dispose = function () {
  85019. if (this.mesh) {
  85020. this.mesh = null;
  85021. this.bone = null;
  85022. _super.prototype.dispose.call(this);
  85023. }
  85024. };
  85025. return BoneAxesViewer;
  85026. }(Debug.AxesViewer));
  85027. Debug.BoneAxesViewer = BoneAxesViewer;
  85028. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85029. })(BABYLON || (BABYLON = {}));
  85030. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85031. var BABYLON;
  85032. (function (BABYLON) {
  85033. var RayHelper = /** @class */ (function () {
  85034. function RayHelper(ray) {
  85035. this.ray = ray;
  85036. }
  85037. RayHelper.CreateAndShow = function (ray, scene, color) {
  85038. var helper = new RayHelper(ray);
  85039. helper.show(scene, color);
  85040. return helper;
  85041. };
  85042. RayHelper.prototype.show = function (scene, color) {
  85043. if (!this._renderFunction && this.ray) {
  85044. var ray = this.ray;
  85045. this._renderFunction = this._render.bind(this);
  85046. this._scene = scene;
  85047. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85048. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85049. if (this._renderFunction) {
  85050. this._scene.registerBeforeRender(this._renderFunction);
  85051. }
  85052. }
  85053. if (color && this._renderLine) {
  85054. this._renderLine.color.copyFrom(color);
  85055. }
  85056. };
  85057. RayHelper.prototype.hide = function () {
  85058. if (this._renderFunction && this._scene) {
  85059. this._scene.unregisterBeforeRender(this._renderFunction);
  85060. this._scene = null;
  85061. this._renderFunction = null;
  85062. if (this._renderLine) {
  85063. this._renderLine.dispose();
  85064. this._renderLine = null;
  85065. }
  85066. this._renderPoints = [];
  85067. }
  85068. };
  85069. RayHelper.prototype._render = function () {
  85070. var ray = this.ray;
  85071. if (!ray) {
  85072. return;
  85073. }
  85074. var point = this._renderPoints[1];
  85075. var len = Math.min(ray.length, 1000000);
  85076. point.copyFrom(ray.direction);
  85077. point.scaleInPlace(len);
  85078. point.addInPlace(ray.origin);
  85079. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85080. };
  85081. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85082. this._attachedToMesh = mesh;
  85083. var ray = this.ray;
  85084. if (!ray) {
  85085. return;
  85086. }
  85087. if (!ray.direction) {
  85088. ray.direction = BABYLON.Vector3.Zero();
  85089. }
  85090. if (!ray.origin) {
  85091. ray.origin = BABYLON.Vector3.Zero();
  85092. }
  85093. if (length) {
  85094. ray.length = length;
  85095. }
  85096. if (!meshSpaceOrigin) {
  85097. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85098. }
  85099. if (!meshSpaceDirection) {
  85100. // -1 so that this will work with Mesh.lookAt
  85101. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85102. }
  85103. if (!this._meshSpaceDirection) {
  85104. this._meshSpaceDirection = meshSpaceDirection.clone();
  85105. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85106. }
  85107. else {
  85108. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85109. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85110. }
  85111. if (!this._updateToMeshFunction) {
  85112. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85113. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85114. }
  85115. this._updateToMesh();
  85116. };
  85117. RayHelper.prototype.detachFromMesh = function () {
  85118. if (this._attachedToMesh) {
  85119. if (this._updateToMeshFunction) {
  85120. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85121. }
  85122. this._attachedToMesh = null;
  85123. this._updateToMeshFunction = null;
  85124. }
  85125. };
  85126. RayHelper.prototype._updateToMesh = function () {
  85127. var ray = this.ray;
  85128. if (!this._attachedToMesh || !ray) {
  85129. return;
  85130. }
  85131. if (this._attachedToMesh._isDisposed) {
  85132. this.detachFromMesh();
  85133. return;
  85134. }
  85135. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85136. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85137. };
  85138. RayHelper.prototype.dispose = function () {
  85139. this.hide();
  85140. this.detachFromMesh();
  85141. this.ray = null;
  85142. };
  85143. return RayHelper;
  85144. }());
  85145. BABYLON.RayHelper = RayHelper;
  85146. })(BABYLON || (BABYLON = {}));
  85147. //# sourceMappingURL=babylon.rayHelper.js.map
  85148. var BABYLON;
  85149. (function (BABYLON) {
  85150. // load the inspector using require, if not present in the global namespace.
  85151. var DebugLayer = /** @class */ (function () {
  85152. function DebugLayer(scene) {
  85153. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85154. this._scene = scene;
  85155. // load inspector using require, if it doesn't exist on the global namespace.
  85156. }
  85157. /** Creates the inspector window. */
  85158. DebugLayer.prototype._createInspector = function (config) {
  85159. if (config === void 0) { config = {}; }
  85160. var popup = config.popup || false;
  85161. var initialTab = config.initialTab || 0;
  85162. var parentElement = config.parentElement || null;
  85163. if (!this._inspector) {
  85164. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85165. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85166. } // else nothing to do,; instance is already existing
  85167. };
  85168. DebugLayer.prototype.isVisible = function () {
  85169. if (!this._inspector) {
  85170. return false;
  85171. }
  85172. return true;
  85173. };
  85174. DebugLayer.prototype.hide = function () {
  85175. if (this._inspector) {
  85176. try {
  85177. this._inspector.dispose();
  85178. }
  85179. catch (e) {
  85180. // If the inspector has been removed directly from the inspector tool
  85181. }
  85182. this._inspector = null;
  85183. }
  85184. };
  85185. DebugLayer.prototype.show = function (config) {
  85186. if (config === void 0) { config = {}; }
  85187. if (typeof this.BJSINSPECTOR == 'undefined') {
  85188. // Load inspector and add it to the DOM
  85189. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85190. }
  85191. else {
  85192. // Otherwise creates the inspector
  85193. this._createInspector(config);
  85194. }
  85195. };
  85196. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85197. return DebugLayer;
  85198. }());
  85199. BABYLON.DebugLayer = DebugLayer;
  85200. })(BABYLON || (BABYLON = {}));
  85201. //# sourceMappingURL=babylon.debugLayer.js.map
  85202. var BABYLON;
  85203. (function (BABYLON) {
  85204. var Debug;
  85205. (function (Debug) {
  85206. /**
  85207. * Used to show the physics impostor around the specific mesh.
  85208. */
  85209. var PhysicsViewer = /** @class */ (function () {
  85210. function PhysicsViewer(scene) {
  85211. this._impostors = [];
  85212. this._meshes = [];
  85213. this._numMeshes = 0;
  85214. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85215. var physicEngine = this._scene.getPhysicsEngine();
  85216. if (physicEngine) {
  85217. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85218. }
  85219. }
  85220. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85221. var plugin = this._physicsEnginePlugin;
  85222. for (var i = 0; i < this._numMeshes; i++) {
  85223. var impostor = this._impostors[i];
  85224. if (!impostor) {
  85225. continue;
  85226. }
  85227. if (impostor.isDisposed) {
  85228. this.hideImpostor(this._impostors[i--]);
  85229. }
  85230. else {
  85231. var mesh = this._meshes[i];
  85232. if (mesh && plugin) {
  85233. plugin.syncMeshWithImpostor(mesh, impostor);
  85234. }
  85235. }
  85236. }
  85237. };
  85238. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85239. if (!this._scene) {
  85240. return;
  85241. }
  85242. for (var i = 0; i < this._numMeshes; i++) {
  85243. if (this._impostors[i] == impostor) {
  85244. return;
  85245. }
  85246. }
  85247. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85248. if (debugMesh) {
  85249. this._impostors[this._numMeshes] = impostor;
  85250. this._meshes[this._numMeshes] = debugMesh;
  85251. if (this._numMeshes === 0) {
  85252. this._renderFunction = this._updateDebugMeshes.bind(this);
  85253. this._scene.registerBeforeRender(this._renderFunction);
  85254. }
  85255. this._numMeshes++;
  85256. }
  85257. };
  85258. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85259. if (!impostor || !this._scene) {
  85260. return;
  85261. }
  85262. var removed = false;
  85263. for (var i = 0; i < this._numMeshes; i++) {
  85264. if (this._impostors[i] == impostor) {
  85265. var mesh = this._meshes[i];
  85266. if (!mesh) {
  85267. continue;
  85268. }
  85269. this._scene.removeMesh(mesh);
  85270. mesh.dispose();
  85271. this._numMeshes--;
  85272. if (this._numMeshes > 0) {
  85273. this._meshes[i] = this._meshes[this._numMeshes];
  85274. this._impostors[i] = this._impostors[this._numMeshes];
  85275. this._meshes[this._numMeshes] = null;
  85276. this._impostors[this._numMeshes] = null;
  85277. }
  85278. else {
  85279. this._meshes[0] = null;
  85280. this._impostors[0] = null;
  85281. }
  85282. removed = true;
  85283. break;
  85284. }
  85285. }
  85286. if (removed && this._numMeshes === 0) {
  85287. this._scene.unregisterBeforeRender(this._renderFunction);
  85288. }
  85289. };
  85290. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85291. if (!this._debugMaterial) {
  85292. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85293. this._debugMaterial.wireframe = true;
  85294. }
  85295. return this._debugMaterial;
  85296. };
  85297. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85298. if (!this._debugBoxMesh) {
  85299. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85300. this._debugBoxMesh.renderingGroupId = 1;
  85301. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85302. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85303. scene.removeMesh(this._debugBoxMesh);
  85304. }
  85305. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85306. };
  85307. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85308. if (!this._debugSphereMesh) {
  85309. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85310. this._debugSphereMesh.renderingGroupId = 1;
  85311. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85312. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85313. scene.removeMesh(this._debugSphereMesh);
  85314. }
  85315. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85316. };
  85317. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85318. var mesh = null;
  85319. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85320. mesh = this._getDebugBoxMesh(scene);
  85321. impostor.getBoxSizeToRef(mesh.scaling);
  85322. }
  85323. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85324. mesh = this._getDebugSphereMesh(scene);
  85325. var radius = impostor.getRadius();
  85326. mesh.scaling.x = radius * 2;
  85327. mesh.scaling.y = radius * 2;
  85328. mesh.scaling.z = radius * 2;
  85329. }
  85330. return mesh;
  85331. };
  85332. PhysicsViewer.prototype.dispose = function () {
  85333. for (var i = 0; i < this._numMeshes; i++) {
  85334. this.hideImpostor(this._impostors[i]);
  85335. }
  85336. if (this._debugBoxMesh) {
  85337. this._debugBoxMesh.dispose();
  85338. }
  85339. if (this._debugSphereMesh) {
  85340. this._debugSphereMesh.dispose();
  85341. }
  85342. if (this._debugMaterial) {
  85343. this._debugMaterial.dispose();
  85344. }
  85345. this._impostors.length = 0;
  85346. this._scene = null;
  85347. this._physicsEnginePlugin = null;
  85348. };
  85349. return PhysicsViewer;
  85350. }());
  85351. Debug.PhysicsViewer = PhysicsViewer;
  85352. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85353. })(BABYLON || (BABYLON = {}));
  85354. //# sourceMappingURL=babylon.physicsViewer.js.map
  85355. var BABYLON;
  85356. (function (BABYLON) {
  85357. var BoundingBoxRenderer = /** @class */ (function () {
  85358. function BoundingBoxRenderer(scene) {
  85359. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85360. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85361. this.showBackLines = true;
  85362. this.renderList = new BABYLON.SmartArray(32);
  85363. this._vertexBuffers = {};
  85364. this._scene = scene;
  85365. }
  85366. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85367. if (this._colorShader) {
  85368. return;
  85369. }
  85370. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85371. attributes: [BABYLON.VertexBuffer.PositionKind],
  85372. uniforms: ["world", "viewProjection", "color"]
  85373. });
  85374. var engine = this._scene.getEngine();
  85375. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85376. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85377. this._createIndexBuffer();
  85378. };
  85379. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85380. var engine = this._scene.getEngine();
  85381. 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]);
  85382. };
  85383. BoundingBoxRenderer.prototype._rebuild = function () {
  85384. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85385. if (vb) {
  85386. vb._rebuild();
  85387. }
  85388. this._createIndexBuffer();
  85389. };
  85390. BoundingBoxRenderer.prototype.reset = function () {
  85391. this.renderList.reset();
  85392. };
  85393. BoundingBoxRenderer.prototype.render = function () {
  85394. if (this.renderList.length === 0) {
  85395. return;
  85396. }
  85397. this._prepareRessources();
  85398. if (!this._colorShader.isReady()) {
  85399. return;
  85400. }
  85401. var engine = this._scene.getEngine();
  85402. engine.setDepthWrite(false);
  85403. this._colorShader._preBind();
  85404. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85405. var boundingBox = this.renderList.data[boundingBoxIndex];
  85406. var min = boundingBox.minimum;
  85407. var max = boundingBox.maximum;
  85408. var diff = max.subtract(min);
  85409. var median = min.add(diff.scale(0.5));
  85410. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85411. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85412. .multiply(boundingBox.getWorldMatrix());
  85413. // VBOs
  85414. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85415. if (this.showBackLines) {
  85416. // Back
  85417. engine.setDepthFunctionToGreaterOrEqual();
  85418. this._scene.resetCachedMaterial();
  85419. this._colorShader.setColor4("color", this.backColor.toColor4());
  85420. this._colorShader.bind(worldMatrix);
  85421. // Draw order
  85422. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85423. }
  85424. // Front
  85425. engine.setDepthFunctionToLess();
  85426. this._scene.resetCachedMaterial();
  85427. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85428. this._colorShader.bind(worldMatrix);
  85429. // Draw order
  85430. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85431. }
  85432. this._colorShader.unbind();
  85433. engine.setDepthFunctionToLessOrEqual();
  85434. engine.setDepthWrite(true);
  85435. };
  85436. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85437. this._prepareRessources();
  85438. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85439. return;
  85440. }
  85441. var engine = this._scene.getEngine();
  85442. engine.setDepthWrite(false);
  85443. engine.setColorWrite(false);
  85444. this._colorShader._preBind();
  85445. var boundingBox = mesh._boundingInfo.boundingBox;
  85446. var min = boundingBox.minimum;
  85447. var max = boundingBox.maximum;
  85448. var diff = max.subtract(min);
  85449. var median = min.add(diff.scale(0.5));
  85450. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85451. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85452. .multiply(boundingBox.getWorldMatrix());
  85453. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85454. engine.setDepthFunctionToLess();
  85455. this._scene.resetCachedMaterial();
  85456. this._colorShader.bind(worldMatrix);
  85457. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85458. this._colorShader.unbind();
  85459. engine.setDepthFunctionToLessOrEqual();
  85460. engine.setDepthWrite(true);
  85461. engine.setColorWrite(true);
  85462. };
  85463. BoundingBoxRenderer.prototype.dispose = function () {
  85464. if (!this._colorShader) {
  85465. return;
  85466. }
  85467. this.renderList.dispose();
  85468. this._colorShader.dispose();
  85469. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85470. if (buffer) {
  85471. buffer.dispose();
  85472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85473. }
  85474. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85475. };
  85476. return BoundingBoxRenderer;
  85477. }());
  85478. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85479. })(BABYLON || (BABYLON = {}));
  85480. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85481. var BABYLON;
  85482. (function (BABYLON) {
  85483. /**
  85484. * Defines a target to use with MorphTargetManager
  85485. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85486. */
  85487. var MorphTarget = /** @class */ (function () {
  85488. /**
  85489. * Creates a new MorphTarget
  85490. * @param name defines the name of the target
  85491. * @param influence defines the influence to use
  85492. */
  85493. function MorphTarget(
  85494. /** defines the name of the target */
  85495. name, influence, scene) {
  85496. if (influence === void 0) { influence = 0; }
  85497. if (scene === void 0) { scene = null; }
  85498. this.name = name;
  85499. /**
  85500. * Gets or sets the list of animations
  85501. */
  85502. this.animations = new Array();
  85503. this._positions = null;
  85504. this._normals = null;
  85505. this._tangents = null;
  85506. /**
  85507. * Observable raised when the influence changes
  85508. */
  85509. this.onInfluenceChanged = new BABYLON.Observable();
  85510. this._animationPropertiesOverride = null;
  85511. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85512. this.influence = influence;
  85513. }
  85514. Object.defineProperty(MorphTarget.prototype, "influence", {
  85515. /**
  85516. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85517. */
  85518. get: function () {
  85519. return this._influence;
  85520. },
  85521. set: function (influence) {
  85522. if (this._influence === influence) {
  85523. return;
  85524. }
  85525. var previous = this._influence;
  85526. this._influence = influence;
  85527. if (this.onInfluenceChanged.hasObservers) {
  85528. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85529. }
  85530. },
  85531. enumerable: true,
  85532. configurable: true
  85533. });
  85534. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85535. /**
  85536. * Gets or sets the animation properties override
  85537. */
  85538. get: function () {
  85539. if (!this._animationPropertiesOverride && this._scene) {
  85540. return this._scene.animationPropertiesOverride;
  85541. }
  85542. return this._animationPropertiesOverride;
  85543. },
  85544. set: function (value) {
  85545. this._animationPropertiesOverride = value;
  85546. },
  85547. enumerable: true,
  85548. configurable: true
  85549. });
  85550. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85551. /**
  85552. * Gets a boolean defining if the target contains position data
  85553. */
  85554. get: function () {
  85555. return !!this._positions;
  85556. },
  85557. enumerable: true,
  85558. configurable: true
  85559. });
  85560. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85561. /**
  85562. * Gets a boolean defining if the target contains normal data
  85563. */
  85564. get: function () {
  85565. return !!this._normals;
  85566. },
  85567. enumerable: true,
  85568. configurable: true
  85569. });
  85570. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85571. /**
  85572. * Gets a boolean defining if the target contains tangent data
  85573. */
  85574. get: function () {
  85575. return !!this._tangents;
  85576. },
  85577. enumerable: true,
  85578. configurable: true
  85579. });
  85580. /**
  85581. * Affects position data to this target
  85582. * @param data defines the position data to use
  85583. */
  85584. MorphTarget.prototype.setPositions = function (data) {
  85585. this._positions = data;
  85586. };
  85587. /**
  85588. * Gets the position data stored in this target
  85589. * @returns a FloatArray containing the position data (or null if not present)
  85590. */
  85591. MorphTarget.prototype.getPositions = function () {
  85592. return this._positions;
  85593. };
  85594. /**
  85595. * Affects normal data to this target
  85596. * @param data defines the normal data to use
  85597. */
  85598. MorphTarget.prototype.setNormals = function (data) {
  85599. this._normals = data;
  85600. };
  85601. /**
  85602. * Gets the normal data stored in this target
  85603. * @returns a FloatArray containing the normal data (or null if not present)
  85604. */
  85605. MorphTarget.prototype.getNormals = function () {
  85606. return this._normals;
  85607. };
  85608. /**
  85609. * Affects tangent data to this target
  85610. * @param data defines the tangent data to use
  85611. */
  85612. MorphTarget.prototype.setTangents = function (data) {
  85613. this._tangents = data;
  85614. };
  85615. /**
  85616. * Gets the tangent data stored in this target
  85617. * @returns a FloatArray containing the tangent data (or null if not present)
  85618. */
  85619. MorphTarget.prototype.getTangents = function () {
  85620. return this._tangents;
  85621. };
  85622. /**
  85623. * Serializes the current target into a Serialization object
  85624. * @returns the serialized object
  85625. */
  85626. MorphTarget.prototype.serialize = function () {
  85627. var serializationObject = {};
  85628. serializationObject.name = this.name;
  85629. serializationObject.influence = this.influence;
  85630. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85631. if (this.hasNormals) {
  85632. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85633. }
  85634. if (this.hasTangents) {
  85635. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85636. }
  85637. // Animations
  85638. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85639. return serializationObject;
  85640. };
  85641. // Statics
  85642. /**
  85643. * Creates a new target from serialized data
  85644. * @param serializationObject defines the serialized data to use
  85645. * @returns a new MorphTarget
  85646. */
  85647. MorphTarget.Parse = function (serializationObject) {
  85648. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85649. result.setPositions(serializationObject.positions);
  85650. if (serializationObject.normals) {
  85651. result.setNormals(serializationObject.normals);
  85652. }
  85653. if (serializationObject.tangents) {
  85654. result.setTangents(serializationObject.tangents);
  85655. }
  85656. // Animations
  85657. if (serializationObject.animations) {
  85658. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85659. var parsedAnimation = serializationObject.animations[animationIndex];
  85660. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85661. }
  85662. }
  85663. return result;
  85664. };
  85665. /**
  85666. * Creates a MorphTarget from mesh data
  85667. * @param mesh defines the source mesh
  85668. * @param name defines the name to use for the new target
  85669. * @param influence defines the influence to attach to the target
  85670. * @returns a new MorphTarget
  85671. */
  85672. MorphTarget.FromMesh = function (mesh, name, influence) {
  85673. if (!name) {
  85674. name = mesh.name;
  85675. }
  85676. var result = new MorphTarget(name, influence, mesh.getScene());
  85677. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85678. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85679. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85680. }
  85681. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85682. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85683. }
  85684. return result;
  85685. };
  85686. return MorphTarget;
  85687. }());
  85688. BABYLON.MorphTarget = MorphTarget;
  85689. })(BABYLON || (BABYLON = {}));
  85690. //# sourceMappingURL=babylon.morphTarget.js.map
  85691. var BABYLON;
  85692. (function (BABYLON) {
  85693. /**
  85694. * This class is used to deform meshes using morphing between different targets
  85695. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85696. */
  85697. var MorphTargetManager = /** @class */ (function () {
  85698. /**
  85699. * Creates a new MorphTargetManager
  85700. * @param scene defines the current scene
  85701. */
  85702. function MorphTargetManager(scene) {
  85703. if (scene === void 0) { scene = null; }
  85704. this._targets = new Array();
  85705. this._targetObservable = new Array();
  85706. this._activeTargets = new BABYLON.SmartArray(16);
  85707. this._supportsNormals = false;
  85708. this._supportsTangents = false;
  85709. this._vertexCount = 0;
  85710. this._uniqueId = 0;
  85711. this._tempInfluences = new Array();
  85712. if (!scene) {
  85713. scene = BABYLON.Engine.LastCreatedScene;
  85714. }
  85715. this._scene = scene;
  85716. if (this._scene) {
  85717. this._scene.morphTargetManagers.push(this);
  85718. this._uniqueId = this._scene.getUniqueId();
  85719. }
  85720. }
  85721. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85722. /**
  85723. * Gets the unique ID of this manager
  85724. */
  85725. get: function () {
  85726. return this._uniqueId;
  85727. },
  85728. enumerable: true,
  85729. configurable: true
  85730. });
  85731. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85732. /**
  85733. * Gets the number of vertices handled by this manager
  85734. */
  85735. get: function () {
  85736. return this._vertexCount;
  85737. },
  85738. enumerable: true,
  85739. configurable: true
  85740. });
  85741. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85742. /**
  85743. * Gets a boolean indicating if this manager supports morphing of normals
  85744. */
  85745. get: function () {
  85746. return this._supportsNormals;
  85747. },
  85748. enumerable: true,
  85749. configurable: true
  85750. });
  85751. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85752. /**
  85753. * Gets a boolean indicating if this manager supports morphing of tangents
  85754. */
  85755. get: function () {
  85756. return this._supportsTangents;
  85757. },
  85758. enumerable: true,
  85759. configurable: true
  85760. });
  85761. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85762. /**
  85763. * Gets the number of targets stored in this manager
  85764. */
  85765. get: function () {
  85766. return this._targets.length;
  85767. },
  85768. enumerable: true,
  85769. configurable: true
  85770. });
  85771. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85772. /**
  85773. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85774. */
  85775. get: function () {
  85776. return this._activeTargets.length;
  85777. },
  85778. enumerable: true,
  85779. configurable: true
  85780. });
  85781. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85782. /**
  85783. * Gets the list of influences (one per target)
  85784. */
  85785. get: function () {
  85786. return this._influences;
  85787. },
  85788. enumerable: true,
  85789. configurable: true
  85790. });
  85791. /**
  85792. * Gets the active target at specified index. An active target is a target with an influence > 0
  85793. * @param index defines the index to check
  85794. * @returns the requested target
  85795. */
  85796. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85797. return this._activeTargets.data[index];
  85798. };
  85799. /**
  85800. * Gets the target at specified index
  85801. * @param index defines the index to check
  85802. * @returns the requested target
  85803. */
  85804. MorphTargetManager.prototype.getTarget = function (index) {
  85805. return this._targets[index];
  85806. };
  85807. /**
  85808. * Add a new target to this manager
  85809. * @param target defines the target to add
  85810. */
  85811. MorphTargetManager.prototype.addTarget = function (target) {
  85812. var _this = this;
  85813. this._targets.push(target);
  85814. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85815. _this._syncActiveTargets(needUpdate);
  85816. }));
  85817. this._syncActiveTargets(true);
  85818. };
  85819. /**
  85820. * Removes a target from the manager
  85821. * @param target defines the target to remove
  85822. */
  85823. MorphTargetManager.prototype.removeTarget = function (target) {
  85824. var index = this._targets.indexOf(target);
  85825. if (index >= 0) {
  85826. this._targets.splice(index, 1);
  85827. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85828. this._syncActiveTargets(true);
  85829. }
  85830. };
  85831. /**
  85832. * Serializes the current manager into a Serialization object
  85833. * @returns the serialized object
  85834. */
  85835. MorphTargetManager.prototype.serialize = function () {
  85836. var serializationObject = {};
  85837. serializationObject.id = this.uniqueId;
  85838. serializationObject.targets = [];
  85839. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85840. var target = _a[_i];
  85841. serializationObject.targets.push(target.serialize());
  85842. }
  85843. return serializationObject;
  85844. };
  85845. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85846. var influenceCount = 0;
  85847. this._activeTargets.reset();
  85848. this._supportsNormals = true;
  85849. this._supportsTangents = true;
  85850. this._vertexCount = 0;
  85851. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85852. var target = _a[_i];
  85853. this._activeTargets.push(target);
  85854. this._tempInfluences[influenceCount++] = target.influence;
  85855. var positions = target.getPositions();
  85856. if (positions) {
  85857. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85858. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85859. var vertexCount = positions.length / 3;
  85860. if (this._vertexCount === 0) {
  85861. this._vertexCount = vertexCount;
  85862. }
  85863. else if (this._vertexCount !== vertexCount) {
  85864. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85865. return;
  85866. }
  85867. }
  85868. }
  85869. if (!this._influences || this._influences.length !== influenceCount) {
  85870. this._influences = new Float32Array(influenceCount);
  85871. }
  85872. for (var index = 0; index < influenceCount; index++) {
  85873. this._influences[index] = this._tempInfluences[index];
  85874. }
  85875. if (needUpdate) {
  85876. this.synchronize();
  85877. }
  85878. };
  85879. /**
  85880. * Syncrhonize the targets with all the meshes using this morph target manager
  85881. */
  85882. MorphTargetManager.prototype.synchronize = function () {
  85883. if (!this._scene) {
  85884. return;
  85885. }
  85886. // Flag meshes as dirty to resync with the active targets
  85887. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85888. var mesh = _a[_i];
  85889. if (mesh.morphTargetManager === this) {
  85890. mesh._syncGeometryWithMorphTargetManager();
  85891. }
  85892. }
  85893. };
  85894. // Statics
  85895. /**
  85896. * Creates a new MorphTargetManager from serialized data
  85897. * @param serializationObject defines the serialized data
  85898. * @param scene defines the hosting scene
  85899. * @returns the new MorphTargetManager
  85900. */
  85901. MorphTargetManager.Parse = function (serializationObject, scene) {
  85902. var result = new MorphTargetManager(scene);
  85903. result._uniqueId = serializationObject.id;
  85904. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85905. var targetData = _a[_i];
  85906. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85907. }
  85908. return result;
  85909. };
  85910. return MorphTargetManager;
  85911. }());
  85912. BABYLON.MorphTargetManager = MorphTargetManager;
  85913. })(BABYLON || (BABYLON = {}));
  85914. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85915. var BABYLON;
  85916. (function (BABYLON) {
  85917. var Octree = /** @class */ (function () {
  85918. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85919. if (maxDepth === void 0) { maxDepth = 2; }
  85920. this.maxDepth = maxDepth;
  85921. this.dynamicContent = new Array();
  85922. this._maxBlockCapacity = maxBlockCapacity || 64;
  85923. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85924. this._creationFunc = creationFunc;
  85925. }
  85926. // Methods
  85927. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85928. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85929. };
  85930. Octree.prototype.addMesh = function (entry) {
  85931. for (var index = 0; index < this.blocks.length; index++) {
  85932. var block = this.blocks[index];
  85933. block.addEntry(entry);
  85934. }
  85935. };
  85936. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85937. this._selectionContent.reset();
  85938. for (var index = 0; index < this.blocks.length; index++) {
  85939. var block = this.blocks[index];
  85940. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85941. }
  85942. if (allowDuplicate) {
  85943. this._selectionContent.concat(this.dynamicContent);
  85944. }
  85945. else {
  85946. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85947. }
  85948. return this._selectionContent;
  85949. };
  85950. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85951. this._selectionContent.reset();
  85952. for (var index = 0; index < this.blocks.length; index++) {
  85953. var block = this.blocks[index];
  85954. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85955. }
  85956. if (allowDuplicate) {
  85957. this._selectionContent.concat(this.dynamicContent);
  85958. }
  85959. else {
  85960. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85961. }
  85962. return this._selectionContent;
  85963. };
  85964. Octree.prototype.intersectsRay = function (ray) {
  85965. this._selectionContent.reset();
  85966. for (var index = 0; index < this.blocks.length; index++) {
  85967. var block = this.blocks[index];
  85968. block.intersectsRay(ray, this._selectionContent);
  85969. }
  85970. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85971. return this._selectionContent;
  85972. };
  85973. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85974. target.blocks = new Array();
  85975. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85976. // Segmenting space
  85977. for (var x = 0; x < 2; x++) {
  85978. for (var y = 0; y < 2; y++) {
  85979. for (var z = 0; z < 2; z++) {
  85980. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85981. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85982. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85983. block.addEntries(entries);
  85984. target.blocks.push(block);
  85985. }
  85986. }
  85987. }
  85988. };
  85989. Octree.CreationFuncForMeshes = function (entry, block) {
  85990. var boundingInfo = entry.getBoundingInfo();
  85991. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85992. block.entries.push(entry);
  85993. }
  85994. };
  85995. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85996. var boundingInfo = entry.getBoundingInfo();
  85997. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85998. block.entries.push(entry);
  85999. }
  86000. };
  86001. return Octree;
  86002. }());
  86003. BABYLON.Octree = Octree;
  86004. })(BABYLON || (BABYLON = {}));
  86005. //# sourceMappingURL=babylon.octree.js.map
  86006. var BABYLON;
  86007. (function (BABYLON) {
  86008. var OctreeBlock = /** @class */ (function () {
  86009. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86010. this.entries = new Array();
  86011. this._boundingVectors = new Array();
  86012. this._capacity = capacity;
  86013. this._depth = depth;
  86014. this._maxDepth = maxDepth;
  86015. this._creationFunc = creationFunc;
  86016. this._minPoint = minPoint;
  86017. this._maxPoint = maxPoint;
  86018. this._boundingVectors.push(minPoint.clone());
  86019. this._boundingVectors.push(maxPoint.clone());
  86020. this._boundingVectors.push(minPoint.clone());
  86021. this._boundingVectors[2].x = maxPoint.x;
  86022. this._boundingVectors.push(minPoint.clone());
  86023. this._boundingVectors[3].y = maxPoint.y;
  86024. this._boundingVectors.push(minPoint.clone());
  86025. this._boundingVectors[4].z = maxPoint.z;
  86026. this._boundingVectors.push(maxPoint.clone());
  86027. this._boundingVectors[5].z = minPoint.z;
  86028. this._boundingVectors.push(maxPoint.clone());
  86029. this._boundingVectors[6].x = minPoint.x;
  86030. this._boundingVectors.push(maxPoint.clone());
  86031. this._boundingVectors[7].y = minPoint.y;
  86032. }
  86033. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86034. // Property
  86035. get: function () {
  86036. return this._capacity;
  86037. },
  86038. enumerable: true,
  86039. configurable: true
  86040. });
  86041. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86042. get: function () {
  86043. return this._minPoint;
  86044. },
  86045. enumerable: true,
  86046. configurable: true
  86047. });
  86048. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86049. get: function () {
  86050. return this._maxPoint;
  86051. },
  86052. enumerable: true,
  86053. configurable: true
  86054. });
  86055. // Methods
  86056. OctreeBlock.prototype.addEntry = function (entry) {
  86057. if (this.blocks) {
  86058. for (var index = 0; index < this.blocks.length; index++) {
  86059. var block = this.blocks[index];
  86060. block.addEntry(entry);
  86061. }
  86062. return;
  86063. }
  86064. this._creationFunc(entry, this);
  86065. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86066. this.createInnerBlocks();
  86067. }
  86068. };
  86069. OctreeBlock.prototype.addEntries = function (entries) {
  86070. for (var index = 0; index < entries.length; index++) {
  86071. var mesh = entries[index];
  86072. this.addEntry(mesh);
  86073. }
  86074. };
  86075. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86076. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86077. if (this.blocks) {
  86078. for (var index = 0; index < this.blocks.length; index++) {
  86079. var block = this.blocks[index];
  86080. block.select(frustumPlanes, selection, allowDuplicate);
  86081. }
  86082. return;
  86083. }
  86084. if (allowDuplicate) {
  86085. selection.concat(this.entries);
  86086. }
  86087. else {
  86088. selection.concatWithNoDuplicate(this.entries);
  86089. }
  86090. }
  86091. };
  86092. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86093. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86094. if (this.blocks) {
  86095. for (var index = 0; index < this.blocks.length; index++) {
  86096. var block = this.blocks[index];
  86097. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86098. }
  86099. return;
  86100. }
  86101. if (allowDuplicate) {
  86102. selection.concat(this.entries);
  86103. }
  86104. else {
  86105. selection.concatWithNoDuplicate(this.entries);
  86106. }
  86107. }
  86108. };
  86109. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86110. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86111. if (this.blocks) {
  86112. for (var index = 0; index < this.blocks.length; index++) {
  86113. var block = this.blocks[index];
  86114. block.intersectsRay(ray, selection);
  86115. }
  86116. return;
  86117. }
  86118. selection.concatWithNoDuplicate(this.entries);
  86119. }
  86120. };
  86121. OctreeBlock.prototype.createInnerBlocks = function () {
  86122. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86123. };
  86124. return OctreeBlock;
  86125. }());
  86126. BABYLON.OctreeBlock = OctreeBlock;
  86127. })(BABYLON || (BABYLON = {}));
  86128. //# sourceMappingURL=babylon.octreeBlock.js.map
  86129. var BABYLON;
  86130. (function (BABYLON) {
  86131. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86132. __extends(VRDistortionCorrectionPostProcess, _super);
  86133. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86134. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86135. 'LensCenter',
  86136. 'Scale',
  86137. 'ScaleIn',
  86138. 'HmdWarpParam'
  86139. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86140. _this._isRightEye = isRightEye;
  86141. _this._distortionFactors = vrMetrics.distortionK;
  86142. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86143. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86144. _this.adaptScaleToCurrentViewport = true;
  86145. _this.onSizeChangedObservable.add(function () {
  86146. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86147. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86148. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86149. });
  86150. _this.onApplyObservable.add(function (effect) {
  86151. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86152. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86153. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86154. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86155. });
  86156. return _this;
  86157. }
  86158. return VRDistortionCorrectionPostProcess;
  86159. }(BABYLON.PostProcess));
  86160. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86161. })(BABYLON || (BABYLON = {}));
  86162. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86163. var BABYLON;
  86164. (function (BABYLON) {
  86165. /**
  86166. * Postprocess used to generate anaglyphic rendering
  86167. */
  86168. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86169. __extends(AnaglyphPostProcess, _super);
  86170. /**
  86171. * Creates a new AnaglyphPostProcess
  86172. * @param name defines postprocess name
  86173. * @param options defines creation options or target ratio scale
  86174. * @param rigCameras defines cameras using this postprocess
  86175. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86176. * @param engine defines hosting engine
  86177. * @param reusable defines if the postprocess will be reused multiple times per frame
  86178. */
  86179. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86180. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86181. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86182. _this.onApplyObservable.add(function (effect) {
  86183. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86184. });
  86185. return _this;
  86186. }
  86187. return AnaglyphPostProcess;
  86188. }(BABYLON.PostProcess));
  86189. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86190. })(BABYLON || (BABYLON = {}));
  86191. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86192. var BABYLON;
  86193. (function (BABYLON) {
  86194. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86195. __extends(StereoscopicInterlacePostProcess, _super);
  86196. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86197. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86198. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86199. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86200. _this.onSizeChangedObservable.add(function () {
  86201. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86202. });
  86203. _this.onApplyObservable.add(function (effect) {
  86204. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86205. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86206. });
  86207. return _this;
  86208. }
  86209. return StereoscopicInterlacePostProcess;
  86210. }(BABYLON.PostProcess));
  86211. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86212. })(BABYLON || (BABYLON = {}));
  86213. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86214. var BABYLON;
  86215. (function (BABYLON) {
  86216. /**
  86217. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86218. * Screen rotation is taken into account.
  86219. */
  86220. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86221. function FreeCameraDeviceOrientationInput() {
  86222. var _this = this;
  86223. this._screenOrientationAngle = 0;
  86224. this._screenQuaternion = new BABYLON.Quaternion();
  86225. this._alpha = 0;
  86226. this._beta = 0;
  86227. this._gamma = 0;
  86228. this._orientationChanged = function () {
  86229. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86230. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86231. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86232. };
  86233. this._deviceOrientation = function (evt) {
  86234. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86235. _this._beta = evt.beta !== null ? evt.beta : 0;
  86236. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86237. };
  86238. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86239. this._orientationChanged();
  86240. }
  86241. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86242. get: function () {
  86243. return this._camera;
  86244. },
  86245. set: function (camera) {
  86246. this._camera = camera;
  86247. if (this._camera != null && !this._camera.rotationQuaternion) {
  86248. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86249. }
  86250. },
  86251. enumerable: true,
  86252. configurable: true
  86253. });
  86254. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86255. window.addEventListener("orientationchange", this._orientationChanged);
  86256. window.addEventListener("deviceorientation", this._deviceOrientation);
  86257. //In certain cases, the attach control is called AFTER orientation was changed,
  86258. //So this is needed.
  86259. this._orientationChanged();
  86260. };
  86261. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86262. window.removeEventListener("orientationchange", this._orientationChanged);
  86263. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86264. };
  86265. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86266. //if no device orientation provided, don't update the rotation.
  86267. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86268. if (!this._alpha)
  86269. return;
  86270. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86271. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86272. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86273. //Mirror on XY Plane
  86274. this._camera.rotationQuaternion.z *= -1;
  86275. this._camera.rotationQuaternion.w *= -1;
  86276. };
  86277. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86278. return "FreeCameraDeviceOrientationInput";
  86279. };
  86280. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86281. return "deviceOrientation";
  86282. };
  86283. return FreeCameraDeviceOrientationInput;
  86284. }());
  86285. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86286. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86287. })(BABYLON || (BABYLON = {}));
  86288. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86289. var BABYLON;
  86290. (function (BABYLON) {
  86291. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86292. function ArcRotateCameraVRDeviceOrientationInput() {
  86293. this.alphaCorrection = 1;
  86294. this.betaCorrection = 1;
  86295. this.gammaCorrection = 1;
  86296. this._alpha = 0;
  86297. this._gamma = 0;
  86298. this._dirty = false;
  86299. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86300. }
  86301. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86302. this.camera.attachControl(element, noPreventDefault);
  86303. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86304. };
  86305. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86306. if (evt.alpha !== null) {
  86307. this._alpha = +evt.alpha | 0;
  86308. }
  86309. if (evt.gamma !== null) {
  86310. this._gamma = +evt.gamma | 0;
  86311. }
  86312. this._dirty = true;
  86313. };
  86314. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86315. if (this._dirty) {
  86316. this._dirty = false;
  86317. if (this._gamma < 0) {
  86318. this._gamma = 180 + this._gamma;
  86319. }
  86320. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86321. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86322. }
  86323. };
  86324. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86325. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86326. };
  86327. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86328. return "ArcRotateCameraVRDeviceOrientationInput";
  86329. };
  86330. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86331. return "VRDeviceOrientation";
  86332. };
  86333. return ArcRotateCameraVRDeviceOrientationInput;
  86334. }());
  86335. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86336. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86337. })(BABYLON || (BABYLON = {}));
  86338. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86339. var BABYLON;
  86340. (function (BABYLON) {
  86341. var VRCameraMetrics = /** @class */ (function () {
  86342. function VRCameraMetrics() {
  86343. this.compensateDistortion = true;
  86344. }
  86345. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86346. get: function () {
  86347. return this.hResolution / (2 * this.vResolution);
  86348. },
  86349. enumerable: true,
  86350. configurable: true
  86351. });
  86352. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86353. get: function () {
  86354. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86355. },
  86356. enumerable: true,
  86357. configurable: true
  86358. });
  86359. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86360. get: function () {
  86361. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86362. var h = (4 * meters) / this.hScreenSize;
  86363. return BABYLON.Matrix.Translation(h, 0, 0);
  86364. },
  86365. enumerable: true,
  86366. configurable: true
  86367. });
  86368. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86369. get: function () {
  86370. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86371. var h = (4 * meters) / this.hScreenSize;
  86372. return BABYLON.Matrix.Translation(-h, 0, 0);
  86373. },
  86374. enumerable: true,
  86375. configurable: true
  86376. });
  86377. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86378. get: function () {
  86379. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86380. },
  86381. enumerable: true,
  86382. configurable: true
  86383. });
  86384. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86385. get: function () {
  86386. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86387. },
  86388. enumerable: true,
  86389. configurable: true
  86390. });
  86391. VRCameraMetrics.GetDefault = function () {
  86392. var result = new VRCameraMetrics();
  86393. result.hResolution = 1280;
  86394. result.vResolution = 800;
  86395. result.hScreenSize = 0.149759993;
  86396. result.vScreenSize = 0.0935999975;
  86397. result.vScreenCenter = 0.0467999987;
  86398. result.eyeToScreenDistance = 0.0410000011;
  86399. result.lensSeparationDistance = 0.0635000020;
  86400. result.interpupillaryDistance = 0.0640000030;
  86401. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86402. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86403. result.postProcessScaleFactor = 1.714605507808412;
  86404. result.lensCenterOffset = 0.151976421;
  86405. return result;
  86406. };
  86407. return VRCameraMetrics;
  86408. }());
  86409. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86410. })(BABYLON || (BABYLON = {}));
  86411. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86412. var BABYLON;
  86413. (function (BABYLON) {
  86414. /**
  86415. * This represents a WebVR camera.
  86416. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86417. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86418. */
  86419. var WebVRFreeCamera = /** @class */ (function (_super) {
  86420. __extends(WebVRFreeCamera, _super);
  86421. /**
  86422. * Instantiates a WebVRFreeCamera.
  86423. * @param name The name of the WebVRFreeCamera
  86424. * @param position The starting anchor position for the camera
  86425. * @param scene The scene the camera belongs to
  86426. * @param webVROptions a set of customizable options for the webVRCamera
  86427. */
  86428. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86429. if (webVROptions === void 0) { webVROptions = {}; }
  86430. var _this = _super.call(this, name, position, scene) || this;
  86431. _this.webVROptions = webVROptions;
  86432. /**
  86433. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86434. */
  86435. _this._vrDevice = null;
  86436. /**
  86437. * The rawPose of the vrDevice.
  86438. */
  86439. _this.rawPose = null;
  86440. _this._specsVersion = "1.1";
  86441. _this._attached = false;
  86442. _this._descendants = [];
  86443. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86444. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86445. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86446. _this._standingMatrix = null;
  86447. /**
  86448. * Represents device position in babylon space.
  86449. */
  86450. _this.devicePosition = BABYLON.Vector3.Zero();
  86451. /**
  86452. * Represents device rotation in babylon space.
  86453. */
  86454. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86455. /**
  86456. * The scale of the device to be used when translating from device space to babylon space.
  86457. */
  86458. _this.deviceScaleFactor = 1;
  86459. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86460. _this._worldToDevice = BABYLON.Matrix.Identity();
  86461. /**
  86462. * References to the webVR controllers for the vrDevice.
  86463. */
  86464. _this.controllers = [];
  86465. /**
  86466. * Emits an event when a controller is attached.
  86467. */
  86468. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86469. /**
  86470. * Emits an event when a controller's mesh has been loaded;
  86471. */
  86472. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86473. /**
  86474. * If the rig cameras be used as parent instead of this camera.
  86475. */
  86476. _this.rigParenting = true;
  86477. _this._defaultHeight = undefined;
  86478. _this._workingVector = BABYLON.Vector3.Zero();
  86479. _this._oneVector = BABYLON.Vector3.One();
  86480. _this._workingMatrix = BABYLON.Matrix.Identity();
  86481. _this._cache.position = BABYLON.Vector3.Zero();
  86482. if (webVROptions.defaultHeight) {
  86483. _this._defaultHeight = webVROptions.defaultHeight;
  86484. _this.position.y = _this._defaultHeight;
  86485. }
  86486. _this.minZ = 0.1;
  86487. //legacy support - the compensation boolean was removed.
  86488. if (arguments.length === 5) {
  86489. _this.webVROptions = arguments[4];
  86490. }
  86491. // default webVR options
  86492. if (_this.webVROptions.trackPosition == undefined) {
  86493. _this.webVROptions.trackPosition = true;
  86494. }
  86495. if (_this.webVROptions.controllerMeshes == undefined) {
  86496. _this.webVROptions.controllerMeshes = true;
  86497. }
  86498. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86499. _this.webVROptions.defaultLightingOnControllers = true;
  86500. }
  86501. _this.rotationQuaternion = new BABYLON.Quaternion();
  86502. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86503. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86504. }
  86505. //enable VR
  86506. var engine = _this.getEngine();
  86507. _this._onVREnabled = function (success) { if (success) {
  86508. _this.initControllers();
  86509. } };
  86510. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86511. engine.initWebVR().add(function (event) {
  86512. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86513. return;
  86514. }
  86515. _this._vrDevice = event.vrDisplay;
  86516. //reset the rig parameters.
  86517. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86518. if (_this._attached) {
  86519. _this.getEngine().enableVR();
  86520. }
  86521. });
  86522. if (typeof (VRFrameData) !== "undefined")
  86523. _this._frameData = new VRFrameData();
  86524. /**
  86525. * The idea behind the following lines:
  86526. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86527. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86528. * the second will not show it correctly.
  86529. *
  86530. * To solve this - each object that has the camera as parent will be added to a protected array.
  86531. * When the rig camera renders, it will take this array and set all of those to be its children.
  86532. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86533. * Amazing!
  86534. */
  86535. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86536. if (camera.parent === _this && _this.rigParenting) {
  86537. _this._descendants = _this.getDescendants(true, function (n) {
  86538. // don't take the cameras or the controllers!
  86539. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86540. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86541. return !isController && !isRigCamera;
  86542. });
  86543. _this._descendants.forEach(function (node) {
  86544. node.parent = camera;
  86545. });
  86546. }
  86547. });
  86548. scene.onAfterCameraRenderObservable.add(function (camera) {
  86549. if (camera.parent === _this && _this.rigParenting) {
  86550. _this._descendants.forEach(function (node) {
  86551. node.parent = _this;
  86552. });
  86553. }
  86554. });
  86555. return _this;
  86556. }
  86557. /**
  86558. * Gets the device distance from the ground in meters.
  86559. * @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.
  86560. */
  86561. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86562. if (this._standingMatrix) {
  86563. // Add standing matrix offset to get real offset from ground in room
  86564. this._standingMatrix.getTranslationToRef(this._workingVector);
  86565. return this._deviceRoomPosition.y + this._workingVector.y;
  86566. }
  86567. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86568. return this._defaultHeight || 0;
  86569. };
  86570. /**
  86571. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86572. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86573. */
  86574. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86575. var _this = this;
  86576. if (callback === void 0) { callback = function (bool) { }; }
  86577. // Use standing matrix if available
  86578. this.getEngine().initWebVRAsync().then(function (result) {
  86579. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86580. callback(false);
  86581. }
  86582. else {
  86583. _this._standingMatrix = new BABYLON.Matrix();
  86584. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86585. if (!_this.getScene().useRightHandedSystem) {
  86586. [2, 6, 8, 9, 14].forEach(function (num) {
  86587. if (_this._standingMatrix) {
  86588. _this._standingMatrix.m[num] *= -1;
  86589. }
  86590. });
  86591. }
  86592. callback(true);
  86593. }
  86594. });
  86595. };
  86596. /**
  86597. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86598. * @returns A promise with a boolean set to if the standing matrix is supported.
  86599. */
  86600. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86601. var _this = this;
  86602. return new Promise(function (res, rej) {
  86603. _this.useStandingMatrix(function (supported) {
  86604. res(supported);
  86605. });
  86606. });
  86607. };
  86608. /**
  86609. * Disposes the camera
  86610. */
  86611. WebVRFreeCamera.prototype.dispose = function () {
  86612. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86613. _super.prototype.dispose.call(this);
  86614. };
  86615. /**
  86616. * Gets a vrController by name.
  86617. * @param name The name of the controller to retreive
  86618. * @returns the controller matching the name specified or null if not found
  86619. */
  86620. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86621. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86622. var gp = _a[_i];
  86623. if (gp.hand === name) {
  86624. return gp;
  86625. }
  86626. }
  86627. return null;
  86628. };
  86629. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86630. /**
  86631. * The controller corrisponding to the users left hand.
  86632. */
  86633. get: function () {
  86634. if (!this._leftController) {
  86635. this._leftController = this.getControllerByName("left");
  86636. }
  86637. return this._leftController;
  86638. },
  86639. enumerable: true,
  86640. configurable: true
  86641. });
  86642. ;
  86643. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86644. /**
  86645. * The controller corrisponding to the users right hand.
  86646. */
  86647. get: function () {
  86648. if (!this._rightController) {
  86649. this._rightController = this.getControllerByName("right");
  86650. }
  86651. return this._rightController;
  86652. },
  86653. enumerable: true,
  86654. configurable: true
  86655. });
  86656. ;
  86657. /**
  86658. * Casts a ray forward from the vrCamera's gaze.
  86659. * @param length Length of the ray (default: 100)
  86660. * @returns the ray corrisponding to the gaze
  86661. */
  86662. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86663. if (length === void 0) { length = 100; }
  86664. if (this.leftCamera) {
  86665. // Use left eye to avoid computation to compute center on every call
  86666. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86667. }
  86668. else {
  86669. return _super.prototype.getForwardRay.call(this, length);
  86670. }
  86671. };
  86672. /**
  86673. * Updates the camera based on device's frame data
  86674. */
  86675. WebVRFreeCamera.prototype._checkInputs = function () {
  86676. if (this._vrDevice && this._vrDevice.isPresenting) {
  86677. this._vrDevice.getFrameData(this._frameData);
  86678. this.updateFromDevice(this._frameData.pose);
  86679. }
  86680. _super.prototype._checkInputs.call(this);
  86681. };
  86682. /**
  86683. * Updates the poseControlled values based on the input device pose.
  86684. * @param poseData Pose coming from the device
  86685. */
  86686. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86687. if (poseData && poseData.orientation) {
  86688. this.rawPose = poseData;
  86689. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86690. if (this.getScene().useRightHandedSystem) {
  86691. this._deviceRoomRotationQuaternion.z *= -1;
  86692. this._deviceRoomRotationQuaternion.w *= -1;
  86693. }
  86694. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86695. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86696. if (this.getScene().useRightHandedSystem) {
  86697. this._deviceRoomPosition.z *= -1;
  86698. }
  86699. }
  86700. }
  86701. };
  86702. /**
  86703. * WebVR's attach control will start broadcasting frames to the device.
  86704. * Note that in certain browsers (chrome for example) this function must be called
  86705. * within a user-interaction callback. Example:
  86706. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86707. *
  86708. * @param element html element to attach the vrDevice to
  86709. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86710. */
  86711. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86712. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86713. this._attached = true;
  86714. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86715. if (this._vrDevice) {
  86716. this.getEngine().enableVR();
  86717. }
  86718. };
  86719. /**
  86720. * Detaches the camera from the html element and disables VR
  86721. *
  86722. * @param element html element to detach from
  86723. */
  86724. WebVRFreeCamera.prototype.detachControl = function (element) {
  86725. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86726. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86727. _super.prototype.detachControl.call(this, element);
  86728. this._attached = false;
  86729. this.getEngine().disableVR();
  86730. };
  86731. /**
  86732. * @returns the name of this class
  86733. */
  86734. WebVRFreeCamera.prototype.getClassName = function () {
  86735. return "WebVRFreeCamera";
  86736. };
  86737. /**
  86738. * Calls resetPose on the vrDisplay
  86739. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86740. */
  86741. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86742. //uses the vrDisplay's "resetPose()".
  86743. //pitch and roll won't be affected.
  86744. this._vrDevice.resetPose();
  86745. };
  86746. /**
  86747. * Updates the rig cameras (left and right eye)
  86748. */
  86749. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86750. var camLeft = this._rigCameras[0];
  86751. var camRight = this._rigCameras[1];
  86752. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86753. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86754. camLeft.position.copyFrom(this._deviceRoomPosition);
  86755. camRight.position.copyFrom(this._deviceRoomPosition);
  86756. };
  86757. /**
  86758. * Updates the cached values of the camera
  86759. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86760. */
  86761. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86762. var _this = this;
  86763. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86764. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86765. if (!this.updateCacheCalled) {
  86766. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86767. this.updateCacheCalled = true;
  86768. this.update();
  86769. }
  86770. // Set working vector to the device position in room space rotated by the new rotation
  86771. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86772. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86773. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86774. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86775. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86776. // Add translation from anchor position
  86777. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86778. this._workingVector.addInPlace(this.position);
  86779. this._workingVector.subtractInPlace(this._cache.position);
  86780. this._deviceToWorld.setTranslation(this._workingVector);
  86781. // Set an inverted matrix to be used when updating the camera
  86782. this._deviceToWorld.invertToRef(this._worldToDevice);
  86783. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86784. this.controllers.forEach(function (controller) {
  86785. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86786. controller.update();
  86787. });
  86788. }
  86789. if (!ignoreParentClass) {
  86790. _super.prototype._updateCache.call(this);
  86791. }
  86792. this.updateCacheCalled = false;
  86793. };
  86794. /**
  86795. * Updates the current device position and rotation in the babylon world
  86796. */
  86797. WebVRFreeCamera.prototype.update = function () {
  86798. // Get current device position in babylon world
  86799. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86800. // Get current device rotation in babylon world
  86801. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86802. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86803. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86804. _super.prototype.update.call(this);
  86805. };
  86806. /**
  86807. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86808. * @returns an identity matrix
  86809. */
  86810. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86811. return BABYLON.Matrix.Identity();
  86812. };
  86813. /**
  86814. * This function is called by the two RIG cameras.
  86815. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86816. */
  86817. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86818. var _this = this;
  86819. // Update the parent camera prior to using a child camera to avoid desynchronization
  86820. var parentCamera = this._cameraRigParams["parentCamera"];
  86821. parentCamera._updateCache();
  86822. //WebVR 1.1
  86823. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86824. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86825. if (!this.getScene().useRightHandedSystem) {
  86826. [2, 6, 8, 9, 14].forEach(function (num) {
  86827. _this._webvrViewMatrix.m[num] *= -1;
  86828. });
  86829. }
  86830. // update the camera rotation matrix
  86831. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86832. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86833. // Computing target and final matrix
  86834. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86835. // should the view matrix be updated with scale and position offset?
  86836. if (parentCamera.deviceScaleFactor !== 1) {
  86837. this._webvrViewMatrix.invert();
  86838. // scale the position, if set
  86839. if (parentCamera.deviceScaleFactor) {
  86840. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86841. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86842. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86843. }
  86844. this._webvrViewMatrix.invert();
  86845. }
  86846. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86847. // Compute global position
  86848. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86849. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86850. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86851. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86852. this._markSyncedWithParent();
  86853. return this._webvrViewMatrix;
  86854. };
  86855. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86856. var _this = this;
  86857. var parentCamera = this.parent;
  86858. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86859. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86860. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86861. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86862. //babylon compatible matrix
  86863. if (!this.getScene().useRightHandedSystem) {
  86864. [8, 9, 10, 11].forEach(function (num) {
  86865. _this._projectionMatrix.m[num] *= -1;
  86866. });
  86867. }
  86868. return this._projectionMatrix;
  86869. };
  86870. /**
  86871. * Initializes the controllers and their meshes
  86872. */
  86873. WebVRFreeCamera.prototype.initControllers = function () {
  86874. var _this = this;
  86875. this.controllers = [];
  86876. var manager = this.getScene().gamepadManager;
  86877. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86878. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86879. var webVrController = gamepad;
  86880. if (webVrController.defaultModel) {
  86881. webVrController.defaultModel.setEnabled(false);
  86882. }
  86883. if (webVrController.hand === "right") {
  86884. _this._rightController = null;
  86885. }
  86886. if (webVrController.hand === "left") {
  86887. _this._leftController = null;
  86888. }
  86889. var controllerIndex = _this.controllers.indexOf(webVrController);
  86890. if (controllerIndex !== -1) {
  86891. _this.controllers.splice(controllerIndex, 1);
  86892. }
  86893. }
  86894. });
  86895. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86896. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86897. var webVrController_1 = gamepad;
  86898. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86899. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86900. if (_this.webVROptions.controllerMeshes) {
  86901. if (webVrController_1.defaultModel) {
  86902. webVrController_1.defaultModel.setEnabled(true);
  86903. }
  86904. else {
  86905. // Load the meshes
  86906. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86907. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86908. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86909. if (_this.webVROptions.defaultLightingOnControllers) {
  86910. if (!_this._lightOnControllers) {
  86911. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86912. }
  86913. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86914. var children = mesh.getChildren();
  86915. if (children.length !== 0) {
  86916. children.forEach(function (mesh) {
  86917. light.includedOnlyMeshes.push(mesh);
  86918. activateLightOnSubMeshes_1(mesh, light);
  86919. });
  86920. }
  86921. };
  86922. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86923. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86924. }
  86925. });
  86926. }
  86927. }
  86928. webVrController_1.attachToPoseControlledCamera(_this);
  86929. // since this is async - sanity check. Is the controller already stored?
  86930. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86931. //add to the controllers array
  86932. _this.controllers.push(webVrController_1);
  86933. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86934. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86935. // So we're overriding setting left & right manually to be sure
  86936. var firstViveWandDetected = false;
  86937. for (var i = 0; i < _this.controllers.length; i++) {
  86938. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86939. if (!firstViveWandDetected) {
  86940. firstViveWandDetected = true;
  86941. _this.controllers[i].hand = "left";
  86942. }
  86943. else {
  86944. _this.controllers[i].hand = "right";
  86945. }
  86946. }
  86947. }
  86948. //did we find enough controllers? Great! let the developer know.
  86949. if (_this.controllers.length >= 2) {
  86950. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86951. }
  86952. }
  86953. }
  86954. });
  86955. };
  86956. return WebVRFreeCamera;
  86957. }(BABYLON.FreeCamera));
  86958. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86959. })(BABYLON || (BABYLON = {}));
  86960. //# sourceMappingURL=babylon.webVRCamera.js.map
  86961. var BABYLON;
  86962. (function (BABYLON) {
  86963. // We're mainly based on the logic defined into the FreeCamera code
  86964. /**
  86965. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86966. * being tilted forward or back and left or right.
  86967. */
  86968. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86969. __extends(DeviceOrientationCamera, _super);
  86970. /**
  86971. * Creates a new device orientation camera
  86972. * @param name The name of the camera
  86973. * @param position The start position camera
  86974. * @param scene The scene the camera belongs to
  86975. */
  86976. function DeviceOrientationCamera(name, position, scene) {
  86977. var _this = _super.call(this, name, position, scene) || this;
  86978. _this._quaternionCache = new BABYLON.Quaternion();
  86979. _this.inputs.addDeviceOrientation();
  86980. return _this;
  86981. }
  86982. /**
  86983. * Gets the current instance class name ("DeviceOrientationCamera").
  86984. * This helps avoiding instanceof at run time.
  86985. * @returns the class name
  86986. */
  86987. DeviceOrientationCamera.prototype.getClassName = function () {
  86988. return "DeviceOrientationCamera";
  86989. };
  86990. /**
  86991. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86992. */
  86993. DeviceOrientationCamera.prototype._checkInputs = function () {
  86994. _super.prototype._checkInputs.call(this);
  86995. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86996. if (this._initialQuaternion) {
  86997. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86998. }
  86999. };
  87000. /**
  87001. * Reset the camera to its default orientation on the specified axis only.
  87002. * @param axis The axis to reset
  87003. */
  87004. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87005. var _this = this;
  87006. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87007. //can only work if this camera has a rotation quaternion already.
  87008. if (!this.rotationQuaternion)
  87009. return;
  87010. if (!this._initialQuaternion) {
  87011. this._initialQuaternion = new BABYLON.Quaternion();
  87012. }
  87013. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87014. ['x', 'y', 'z'].forEach(function (axisName) {
  87015. if (!axis[axisName]) {
  87016. _this._initialQuaternion[axisName] = 0;
  87017. }
  87018. else {
  87019. _this._initialQuaternion[axisName] *= -1;
  87020. }
  87021. });
  87022. this._initialQuaternion.normalize();
  87023. //force rotation update
  87024. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87025. };
  87026. return DeviceOrientationCamera;
  87027. }(BABYLON.FreeCamera));
  87028. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87029. })(BABYLON || (BABYLON = {}));
  87030. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87031. var BABYLON;
  87032. (function (BABYLON) {
  87033. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87034. __extends(VRDeviceOrientationFreeCamera, _super);
  87035. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87036. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87037. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87038. var _this = _super.call(this, name, position, scene) || this;
  87039. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87040. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87041. return _this;
  87042. }
  87043. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87044. return "VRDeviceOrientationFreeCamera";
  87045. };
  87046. return VRDeviceOrientationFreeCamera;
  87047. }(BABYLON.DeviceOrientationCamera));
  87048. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87049. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87050. __extends(VRDeviceOrientationGamepadCamera, _super);
  87051. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87052. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87053. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87054. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87055. _this.inputs.addGamepad();
  87056. return _this;
  87057. }
  87058. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87059. return "VRDeviceOrientationGamepadCamera";
  87060. };
  87061. return VRDeviceOrientationGamepadCamera;
  87062. }(VRDeviceOrientationFreeCamera));
  87063. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87064. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87065. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87066. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87067. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87068. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87069. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87070. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87071. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87072. _this.inputs.addVRDeviceOrientation();
  87073. return _this;
  87074. }
  87075. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87076. return "VRDeviceOrientationArcRotateCamera";
  87077. };
  87078. return VRDeviceOrientationArcRotateCamera;
  87079. }(BABYLON.ArcRotateCamera));
  87080. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87081. })(BABYLON || (BABYLON = {}));
  87082. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87083. var BABYLON;
  87084. (function (BABYLON) {
  87085. /**
  87086. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87087. */
  87088. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87089. __extends(AnaglyphFreeCamera, _super);
  87090. /**
  87091. * Creates a new AnaglyphFreeCamera
  87092. * @param name defines camera name
  87093. * @param position defines initial position
  87094. * @param interaxialDistance defines distance between each color axis
  87095. * @param scene defines the hosting scene
  87096. */
  87097. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87098. var _this = _super.call(this, name, position, scene) || this;
  87099. _this.interaxialDistance = interaxialDistance;
  87100. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87101. return _this;
  87102. }
  87103. /**
  87104. * Gets camera class name
  87105. * @returns AnaglyphFreeCamera
  87106. */
  87107. AnaglyphFreeCamera.prototype.getClassName = function () {
  87108. return "AnaglyphFreeCamera";
  87109. };
  87110. return AnaglyphFreeCamera;
  87111. }(BABYLON.FreeCamera));
  87112. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87113. /**
  87114. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87115. */
  87116. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87117. __extends(AnaglyphArcRotateCamera, _super);
  87118. /**
  87119. * Creates a new AnaglyphArcRotateCamera
  87120. * @param name defines camera name
  87121. * @param alpha defines alpha angle (in radians)
  87122. * @param beta defines beta angle (in radians)
  87123. * @param radius defines radius
  87124. * @param target defines camera target
  87125. * @param interaxialDistance defines distance between each color axis
  87126. * @param scene defines the hosting scene
  87127. */
  87128. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87129. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87130. _this.interaxialDistance = interaxialDistance;
  87131. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87132. return _this;
  87133. }
  87134. /**
  87135. * Gets camera class name
  87136. * @returns AnaglyphArcRotateCamera
  87137. */
  87138. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87139. return "AnaglyphArcRotateCamera";
  87140. };
  87141. return AnaglyphArcRotateCamera;
  87142. }(BABYLON.ArcRotateCamera));
  87143. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87144. /**
  87145. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87146. */
  87147. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87148. __extends(AnaglyphGamepadCamera, _super);
  87149. /**
  87150. * Creates a new AnaglyphGamepadCamera
  87151. * @param name defines camera name
  87152. * @param position defines initial position
  87153. * @param interaxialDistance defines distance between each color axis
  87154. * @param scene defines the hosting scene
  87155. */
  87156. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87157. var _this = _super.call(this, name, position, scene) || this;
  87158. _this.interaxialDistance = interaxialDistance;
  87159. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87160. return _this;
  87161. }
  87162. /**
  87163. * Gets camera class name
  87164. * @returns AnaglyphGamepadCamera
  87165. */
  87166. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87167. return "AnaglyphGamepadCamera";
  87168. };
  87169. return AnaglyphGamepadCamera;
  87170. }(BABYLON.GamepadCamera));
  87171. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87172. /**
  87173. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87174. */
  87175. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87176. __extends(AnaglyphUniversalCamera, _super);
  87177. /**
  87178. * Creates a new AnaglyphUniversalCamera
  87179. * @param name defines camera name
  87180. * @param position defines initial position
  87181. * @param interaxialDistance defines distance between each color axis
  87182. * @param scene defines the hosting scene
  87183. */
  87184. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87185. var _this = _super.call(this, name, position, scene) || this;
  87186. _this.interaxialDistance = interaxialDistance;
  87187. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87188. return _this;
  87189. }
  87190. /**
  87191. * Gets camera class name
  87192. * @returns AnaglyphUniversalCamera
  87193. */
  87194. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87195. return "AnaglyphUniversalCamera";
  87196. };
  87197. return AnaglyphUniversalCamera;
  87198. }(BABYLON.UniversalCamera));
  87199. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87200. /**
  87201. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87202. */
  87203. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87204. __extends(StereoscopicFreeCamera, _super);
  87205. /**
  87206. * Creates a new StereoscopicFreeCamera
  87207. * @param name defines camera name
  87208. * @param position defines initial position
  87209. * @param interaxialDistance defines distance between each color axis
  87210. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87211. * @param scene defines the hosting scene
  87212. */
  87213. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87214. var _this = _super.call(this, name, position, scene) || this;
  87215. _this.interaxialDistance = interaxialDistance;
  87216. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87217. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87218. return _this;
  87219. }
  87220. /**
  87221. * Gets camera class name
  87222. * @returns StereoscopicFreeCamera
  87223. */
  87224. StereoscopicFreeCamera.prototype.getClassName = function () {
  87225. return "StereoscopicFreeCamera";
  87226. };
  87227. return StereoscopicFreeCamera;
  87228. }(BABYLON.FreeCamera));
  87229. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87230. /**
  87231. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87232. */
  87233. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87234. __extends(StereoscopicArcRotateCamera, _super);
  87235. /**
  87236. * Creates a new StereoscopicArcRotateCamera
  87237. * @param name defines camera name
  87238. * @param alpha defines alpha angle (in radians)
  87239. * @param beta defines beta angle (in radians)
  87240. * @param radius defines radius
  87241. * @param target defines camera target
  87242. * @param interaxialDistance defines distance between each color axis
  87243. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87244. * @param scene defines the hosting scene
  87245. */
  87246. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87247. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87248. _this.interaxialDistance = interaxialDistance;
  87249. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87250. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87251. return _this;
  87252. }
  87253. /**
  87254. * Gets camera class name
  87255. * @returns StereoscopicArcRotateCamera
  87256. */
  87257. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87258. return "StereoscopicArcRotateCamera";
  87259. };
  87260. return StereoscopicArcRotateCamera;
  87261. }(BABYLON.ArcRotateCamera));
  87262. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87263. /**
  87264. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87265. */
  87266. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87267. __extends(StereoscopicGamepadCamera, _super);
  87268. /**
  87269. * Creates a new StereoscopicGamepadCamera
  87270. * @param name defines camera name
  87271. * @param position defines initial position
  87272. * @param interaxialDistance defines distance between each color axis
  87273. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87274. * @param scene defines the hosting scene
  87275. */
  87276. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87277. var _this = _super.call(this, name, position, scene) || this;
  87278. _this.interaxialDistance = interaxialDistance;
  87279. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87280. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87281. return _this;
  87282. }
  87283. /**
  87284. * Gets camera class name
  87285. * @returns StereoscopicGamepadCamera
  87286. */
  87287. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87288. return "StereoscopicGamepadCamera";
  87289. };
  87290. return StereoscopicGamepadCamera;
  87291. }(BABYLON.GamepadCamera));
  87292. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87293. /**
  87294. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87295. */
  87296. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87297. __extends(StereoscopicUniversalCamera, _super);
  87298. /**
  87299. * Creates a new StereoscopicUniversalCamera
  87300. * @param name defines camera name
  87301. * @param position defines initial position
  87302. * @param interaxialDistance defines distance between each color axis
  87303. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87304. * @param scene defines the hosting scene
  87305. */
  87306. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87307. var _this = _super.call(this, name, position, scene) || this;
  87308. _this.interaxialDistance = interaxialDistance;
  87309. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87310. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87311. return _this;
  87312. }
  87313. /**
  87314. * Gets camera class name
  87315. * @returns StereoscopicUniversalCamera
  87316. */
  87317. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87318. return "StereoscopicUniversalCamera";
  87319. };
  87320. return StereoscopicUniversalCamera;
  87321. }(BABYLON.UniversalCamera));
  87322. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87323. })(BABYLON || (BABYLON = {}));
  87324. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87325. var BABYLON;
  87326. (function (BABYLON) {
  87327. var VRExperienceHelperGazer = /** @class */ (function () {
  87328. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87329. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87330. this.scene = scene;
  87331. this._pointerDownOnMeshAsked = false;
  87332. this._isActionableMesh = false;
  87333. this._teleportationRequestInitiated = false;
  87334. this._teleportationBackRequestInitiated = false;
  87335. this._rotationRightAsked = false;
  87336. this._rotationLeftAsked = false;
  87337. this._dpadPressed = true;
  87338. this._activePointer = false;
  87339. this._id = VRExperienceHelperGazer._idCounter++;
  87340. // Gaze tracker
  87341. if (!gazeTrackerToClone) {
  87342. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87343. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87344. this._gazeTracker.isPickable = false;
  87345. this._gazeTracker.isVisible = false;
  87346. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87347. targetMat.specularColor = BABYLON.Color3.Black();
  87348. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87349. targetMat.backFaceCulling = false;
  87350. this._gazeTracker.material = targetMat;
  87351. }
  87352. else {
  87353. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87354. }
  87355. }
  87356. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87357. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87358. };
  87359. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87360. this._pointerDownOnMeshAsked = true;
  87361. if (this._currentMeshSelected && this._currentHit) {
  87362. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87363. }
  87364. };
  87365. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87366. if (this._currentMeshSelected && this._currentHit) {
  87367. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87368. }
  87369. this._pointerDownOnMeshAsked = false;
  87370. };
  87371. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87372. this._activePointer = true;
  87373. };
  87374. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87375. this._activePointer = false;
  87376. };
  87377. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87378. if (distance === void 0) { distance = 100; }
  87379. };
  87380. VRExperienceHelperGazer.prototype.dispose = function () {
  87381. this._interactionsEnabled = false;
  87382. this._teleportationEnabled = false;
  87383. if (this._gazeTracker) {
  87384. this._gazeTracker.dispose();
  87385. }
  87386. };
  87387. VRExperienceHelperGazer._idCounter = 0;
  87388. return VRExperienceHelperGazer;
  87389. }());
  87390. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87391. __extends(VRExperienceHelperControllerGazer, _super);
  87392. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87393. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87394. _this.webVRController = webVRController;
  87395. // Laser pointer
  87396. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87397. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87398. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87399. laserPointerMaterial.alpha = 0.6;
  87400. _this._laserPointer.material = laserPointerMaterial;
  87401. _this._laserPointer.rotation.x = Math.PI / 2;
  87402. _this._laserPointer.position.z = -0.5;
  87403. _this._laserPointer.isVisible = false;
  87404. if (!webVRController.mesh) {
  87405. // Create an empty mesh that is used prior to loading the high quality model
  87406. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87407. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87408. preloadPointerPose.rotation.x = -0.7;
  87409. preloadMesh.addChild(preloadPointerPose);
  87410. webVRController.attachToMesh(preloadMesh);
  87411. }
  87412. _this._setLaserPointerParent(webVRController.mesh);
  87413. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87414. _this._setLaserPointerParent(mesh);
  87415. });
  87416. return _this;
  87417. }
  87418. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87419. return this.webVRController.getForwardRay(length);
  87420. };
  87421. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87422. _super.prototype._activatePointer.call(this);
  87423. this._laserPointer.isVisible = true;
  87424. };
  87425. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87426. _super.prototype._deactivatePointer.call(this);
  87427. this._laserPointer.isVisible = false;
  87428. };
  87429. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87430. this._laserPointer.material.emissiveColor = color;
  87431. };
  87432. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87433. var makeNotPick = function (root) {
  87434. root.name += " laserPointer";
  87435. root.getChildMeshes().forEach(function (c) {
  87436. makeNotPick(c);
  87437. });
  87438. };
  87439. makeNotPick(mesh);
  87440. var childMeshes = mesh.getChildMeshes();
  87441. this.webVRController._pointingPoseNode = null;
  87442. for (var i = 0; i < childMeshes.length; i++) {
  87443. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87444. mesh = childMeshes[i];
  87445. this.webVRController._pointingPoseNode = mesh;
  87446. break;
  87447. }
  87448. }
  87449. this._laserPointer.parent = mesh;
  87450. };
  87451. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87452. if (distance === void 0) { distance = 100; }
  87453. this._laserPointer.scaling.y = distance;
  87454. this._laserPointer.position.z = -distance / 2;
  87455. };
  87456. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87457. _super.prototype.dispose.call(this);
  87458. this._laserPointer.dispose();
  87459. if (this._meshAttachedObserver) {
  87460. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87461. }
  87462. };
  87463. return VRExperienceHelperControllerGazer;
  87464. }(VRExperienceHelperGazer));
  87465. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87466. __extends(VRExperienceHelperCameraGazer, _super);
  87467. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87468. var _this = _super.call(this, scene) || this;
  87469. _this.getCamera = getCamera;
  87470. return _this;
  87471. }
  87472. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87473. var camera = this.getCamera();
  87474. if (camera) {
  87475. return camera.getForwardRay(length);
  87476. }
  87477. else {
  87478. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87479. }
  87480. };
  87481. return VRExperienceHelperCameraGazer;
  87482. }(VRExperienceHelperGazer));
  87483. /**
  87484. * Helps to quickly add VR support to an existing scene.
  87485. * See http://doc.babylonjs.com/how_to/webvr_helper
  87486. */
  87487. var VRExperienceHelper = /** @class */ (function () {
  87488. /**
  87489. * Instantiates a VRExperienceHelper.
  87490. * Helps to quickly add VR support to an existing scene.
  87491. * @param scene The scene the VRExperienceHelper belongs to.
  87492. * @param webVROptions Options to modify the vr experience helper's behavior.
  87493. */
  87494. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87495. if (webVROptions === void 0) { webVROptions = {}; }
  87496. var _this = this;
  87497. this.webVROptions = webVROptions;
  87498. // Can the system support WebVR, even if a headset isn't plugged in?
  87499. this._webVRsupported = false;
  87500. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87501. this._webVRready = false;
  87502. // Are we waiting for the requestPresent callback to complete?
  87503. this._webVRrequesting = false;
  87504. // Are we presenting to the headset right now?
  87505. this._webVRpresenting = false;
  87506. // Are we presenting in the fullscreen fallback?
  87507. this._fullscreenVRpresenting = false;
  87508. /**
  87509. * Observable raised when entering VR.
  87510. */
  87511. this.onEnteringVRObservable = new BABYLON.Observable();
  87512. /**
  87513. * Observable raised when exiting VR.
  87514. */
  87515. this.onExitingVRObservable = new BABYLON.Observable();
  87516. /**
  87517. * Observable raised when controller mesh is loaded.
  87518. */
  87519. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87520. this._useCustomVRButton = false;
  87521. this._teleportationRequested = false;
  87522. this._teleportActive = false;
  87523. this._floorMeshesCollection = [];
  87524. this._rotationAllowed = true;
  87525. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87526. this._isDefaultTeleportationTarget = true;
  87527. this._teleportationFillColor = "#444444";
  87528. this._teleportationBorderColor = "#FFFFFF";
  87529. this._rotationAngle = 0;
  87530. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87531. this._padSensibilityUp = 0.65;
  87532. this._padSensibilityDown = 0.35;
  87533. this.leftController = null;
  87534. this.rightController = null;
  87535. /**
  87536. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87537. */
  87538. this.onNewMeshSelected = new BABYLON.Observable();
  87539. /**
  87540. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87541. */
  87542. this.onNewMeshPicked = new BABYLON.Observable();
  87543. /**
  87544. * Observable raised before camera teleportation
  87545. */
  87546. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87547. /**
  87548. * Observable raised after camera teleportation
  87549. */
  87550. this.onAfterCameraTeleport = new BABYLON.Observable();
  87551. /**
  87552. * Observable raised when current selected mesh gets unselected
  87553. */
  87554. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87555. /**
  87556. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87557. */
  87558. this.teleportationEnabled = true;
  87559. this._teleportationInitialized = false;
  87560. this._interactionsEnabled = false;
  87561. this._interactionsRequested = false;
  87562. this._displayGaze = true;
  87563. this._displayLaserPointer = true;
  87564. this._onResize = function () {
  87565. _this.moveButtonToBottomRight();
  87566. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87567. _this.exitVR();
  87568. }
  87569. };
  87570. this._onFullscreenChange = function () {
  87571. if (document.fullscreen !== undefined) {
  87572. _this._fullscreenVRpresenting = document.fullscreen;
  87573. }
  87574. else if (document.mozFullScreen !== undefined) {
  87575. _this._fullscreenVRpresenting = document.mozFullScreen;
  87576. }
  87577. else if (document.webkitIsFullScreen !== undefined) {
  87578. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87579. }
  87580. else if (document.msIsFullScreen !== undefined) {
  87581. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87582. }
  87583. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87584. _this.exitVR();
  87585. if (!_this._useCustomVRButton) {
  87586. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87587. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87588. }
  87589. }
  87590. };
  87591. this.beforeRender = function () {
  87592. if (_this.leftController && _this.leftController._activePointer) {
  87593. _this._castRayAndSelectObject(_this.leftController);
  87594. }
  87595. if (_this.rightController && _this.rightController._activePointer) {
  87596. _this._castRayAndSelectObject(_this.rightController);
  87597. }
  87598. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87599. _this._castRayAndSelectObject(_this._cameraGazer);
  87600. }
  87601. else {
  87602. _this._cameraGazer._gazeTracker.isVisible = false;
  87603. }
  87604. };
  87605. this._onNewGamepadConnected = function (gamepad) {
  87606. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87607. if (gamepad.leftStick) {
  87608. gamepad.onleftstickchanged(function (stickValues) {
  87609. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87610. // Listening to classic/xbox gamepad only if no VR controller is active
  87611. if ((!_this.leftController && !_this.rightController) ||
  87612. ((_this.leftController && !_this.leftController._activePointer) &&
  87613. (_this.rightController && !_this.rightController._activePointer))) {
  87614. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87615. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87616. }
  87617. }
  87618. });
  87619. }
  87620. if (gamepad.rightStick) {
  87621. gamepad.onrightstickchanged(function (stickValues) {
  87622. if (_this._teleportationInitialized) {
  87623. _this._checkRotate(stickValues, _this._cameraGazer);
  87624. }
  87625. });
  87626. }
  87627. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87628. gamepad.onbuttondown(function (buttonPressed) {
  87629. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87630. _this._cameraGazer._selectionPointerDown();
  87631. }
  87632. });
  87633. gamepad.onbuttonup(function (buttonPressed) {
  87634. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87635. _this._cameraGazer._selectionPointerUp();
  87636. }
  87637. });
  87638. }
  87639. }
  87640. else {
  87641. var webVRController = gamepad;
  87642. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87643. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87644. _this.rightController = controller;
  87645. }
  87646. else {
  87647. _this.leftController = controller;
  87648. }
  87649. _this._tryEnableInteractionOnController(controller);
  87650. }
  87651. };
  87652. // 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
  87653. this._tryEnableInteractionOnController = function (controller) {
  87654. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87655. _this._enableInteractionOnController(controller);
  87656. }
  87657. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87658. _this._enableTeleportationOnController(controller);
  87659. }
  87660. };
  87661. this._onNewGamepadDisconnected = function (gamepad) {
  87662. if (gamepad instanceof BABYLON.WebVRController) {
  87663. if (gamepad.hand === "left" && _this.leftController != null) {
  87664. _this.leftController.dispose();
  87665. _this.leftController = null;
  87666. }
  87667. if (gamepad.hand === "right" && _this.rightController != null) {
  87668. _this.rightController.dispose();
  87669. _this.rightController = null;
  87670. }
  87671. }
  87672. };
  87673. this._workingVector = BABYLON.Vector3.Zero();
  87674. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87675. this._workingMatrix = BABYLON.Matrix.Identity();
  87676. this._scene = scene;
  87677. this._canvas = scene.getEngine().getRenderingCanvas();
  87678. // Parse options
  87679. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87680. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87681. }
  87682. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87683. webVROptions.createDeviceOrientationCamera = true;
  87684. }
  87685. if (webVROptions.defaultHeight === undefined) {
  87686. webVROptions.defaultHeight = 1.7;
  87687. }
  87688. if (webVROptions.useCustomVRButton) {
  87689. this._useCustomVRButton = true;
  87690. if (webVROptions.customVRButton) {
  87691. this._btnVR = webVROptions.customVRButton;
  87692. }
  87693. }
  87694. if (webVROptions.rayLength) {
  87695. this._rayLength = webVROptions.rayLength;
  87696. }
  87697. this._defaultHeight = webVROptions.defaultHeight;
  87698. if (webVROptions.positionScale) {
  87699. this._rayLength *= webVROptions.positionScale;
  87700. this._defaultHeight *= webVROptions.positionScale;
  87701. }
  87702. // Set position
  87703. if (this._scene.activeCamera) {
  87704. this._position = this._scene.activeCamera.position.clone();
  87705. }
  87706. else {
  87707. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87708. }
  87709. // Set non-vr camera
  87710. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87711. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87712. // Copy data from existing camera
  87713. if (this._scene.activeCamera) {
  87714. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87715. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87716. // Set rotation from previous camera
  87717. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87718. var targetCamera = this._scene.activeCamera;
  87719. if (targetCamera.rotationQuaternion) {
  87720. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87721. }
  87722. else {
  87723. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87724. }
  87725. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87726. }
  87727. }
  87728. this._scene.activeCamera = this._deviceOrientationCamera;
  87729. if (this._canvas) {
  87730. this._scene.activeCamera.attachControl(this._canvas);
  87731. }
  87732. }
  87733. else {
  87734. this._existingCamera = this._scene.activeCamera;
  87735. }
  87736. // Create VR cameras
  87737. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87738. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87739. }
  87740. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87741. this._webVRCamera.useStandingMatrix();
  87742. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87743. // Create default button
  87744. if (!this._useCustomVRButton) {
  87745. this._btnVR = document.createElement("BUTTON");
  87746. this._btnVR.className = "babylonVRicon";
  87747. this._btnVR.id = "babylonVRiconbtn";
  87748. this._btnVR.title = "Click to switch to VR";
  87749. 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) }";
  87750. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87751. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87752. // css += ".babylonVRicon.vrdisplaysupported { }";
  87753. // css += ".babylonVRicon.vrdisplayready { }";
  87754. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87755. var style = document.createElement('style');
  87756. style.appendChild(document.createTextNode(css));
  87757. document.getElementsByTagName('head')[0].appendChild(style);
  87758. this.moveButtonToBottomRight();
  87759. }
  87760. // VR button click event
  87761. if (this._btnVR) {
  87762. this._btnVR.addEventListener("click", function () {
  87763. if (!_this.isInVRMode) {
  87764. _this.enterVR();
  87765. }
  87766. else {
  87767. _this.exitVR();
  87768. }
  87769. });
  87770. }
  87771. // Window events
  87772. window.addEventListener("resize", this._onResize);
  87773. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87774. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87775. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87776. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87777. // Display vr button when headset is connected
  87778. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87779. this.displayVRButton();
  87780. }
  87781. else {
  87782. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87783. if (e.vrDisplay) {
  87784. _this.displayVRButton();
  87785. }
  87786. });
  87787. }
  87788. // Exiting VR mode using 'ESC' key on desktop
  87789. this._onKeyDown = function (event) {
  87790. if (event.keyCode === 27 && _this.isInVRMode) {
  87791. _this.exitVR();
  87792. }
  87793. };
  87794. document.addEventListener("keydown", this._onKeyDown);
  87795. // Exiting VR mode double tapping the touch screen
  87796. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87797. if (_this.isInVRMode) {
  87798. _this.exitVR();
  87799. if (_this._fullscreenVRpresenting) {
  87800. _this._scene.getEngine().switchFullscreen(true);
  87801. }
  87802. }
  87803. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87804. // Listen for WebVR display changes
  87805. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87806. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87807. this._onVRRequestPresentStart = function () {
  87808. _this._webVRrequesting = true;
  87809. _this.updateButtonVisibility();
  87810. };
  87811. this._onVRRequestPresentComplete = function (success) {
  87812. _this._webVRrequesting = false;
  87813. _this.updateButtonVisibility();
  87814. };
  87815. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87816. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87817. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87818. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87819. scene.onDisposeObservable.add(function () {
  87820. _this.dispose();
  87821. });
  87822. // Gamepad connection events
  87823. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87824. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87825. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87826. this.updateButtonVisibility();
  87827. //create easing functions
  87828. this._circleEase = new BABYLON.CircleEase();
  87829. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87830. }
  87831. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87832. /** Return this.onEnteringVRObservable
  87833. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87834. */
  87835. get: function () {
  87836. return this.onEnteringVRObservable;
  87837. },
  87838. enumerable: true,
  87839. configurable: true
  87840. });
  87841. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87842. /** Return this.onExitingVRObservable
  87843. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87844. */
  87845. get: function () {
  87846. return this.onExitingVRObservable;
  87847. },
  87848. enumerable: true,
  87849. configurable: true
  87850. });
  87851. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87852. /** Return this.onControllerMeshLoadedObservable
  87853. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87854. */
  87855. get: function () {
  87856. return this.onControllerMeshLoadedObservable;
  87857. },
  87858. enumerable: true,
  87859. configurable: true
  87860. });
  87861. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87862. /**
  87863. * The mesh used to display where the user is going to teleport.
  87864. */
  87865. get: function () {
  87866. return this._teleportationTarget;
  87867. },
  87868. /**
  87869. * Sets the mesh to be used to display where the user is going to teleport.
  87870. */
  87871. set: function (value) {
  87872. if (value) {
  87873. value.name = "teleportationTarget";
  87874. this._isDefaultTeleportationTarget = false;
  87875. this._teleportationTarget = value;
  87876. }
  87877. },
  87878. enumerable: true,
  87879. configurable: true
  87880. });
  87881. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87882. /**
  87883. * The mesh used to display where the user is selecting,
  87884. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87885. * See http://doc.babylonjs.com/resources/baking_transformations
  87886. */
  87887. get: function () {
  87888. return this._cameraGazer._gazeTracker;
  87889. },
  87890. set: function (value) {
  87891. if (value) {
  87892. this._cameraGazer._gazeTracker = value;
  87893. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87894. this._cameraGazer._gazeTracker.isPickable = false;
  87895. this._cameraGazer._gazeTracker.isVisible = false;
  87896. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87897. if (this.leftController) {
  87898. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87899. }
  87900. if (this.rightController) {
  87901. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87902. }
  87903. }
  87904. },
  87905. enumerable: true,
  87906. configurable: true
  87907. });
  87908. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87909. /**
  87910. * If the ray of the gaze should be displayed.
  87911. */
  87912. get: function () {
  87913. return this._displayGaze;
  87914. },
  87915. /**
  87916. * Sets if the ray of the gaze should be displayed.
  87917. */
  87918. set: function (value) {
  87919. this._displayGaze = value;
  87920. if (!value) {
  87921. this._cameraGazer._gazeTracker.isVisible = false;
  87922. if (this.leftController) {
  87923. this.leftController._gazeTracker.isVisible = false;
  87924. }
  87925. if (this.rightController) {
  87926. this.rightController._gazeTracker.isVisible = false;
  87927. }
  87928. }
  87929. },
  87930. enumerable: true,
  87931. configurable: true
  87932. });
  87933. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87934. /**
  87935. * If the ray of the LaserPointer should be displayed.
  87936. */
  87937. get: function () {
  87938. return this._displayLaserPointer;
  87939. },
  87940. /**
  87941. * Sets if the ray of the LaserPointer should be displayed.
  87942. */
  87943. set: function (value) {
  87944. this._displayLaserPointer = value;
  87945. if (!value) {
  87946. if (this.rightController) {
  87947. this.rightController._deactivatePointer();
  87948. this.rightController._gazeTracker.isVisible = false;
  87949. }
  87950. if (this.leftController) {
  87951. this.leftController._deactivatePointer();
  87952. this.leftController._gazeTracker.isVisible = false;
  87953. }
  87954. }
  87955. else {
  87956. if (this.rightController) {
  87957. this.rightController._activatePointer();
  87958. }
  87959. if (this.leftController) {
  87960. this.leftController._activatePointer();
  87961. }
  87962. }
  87963. },
  87964. enumerable: true,
  87965. configurable: true
  87966. });
  87967. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87968. /**
  87969. * The deviceOrientationCamera used as the camera when not in VR.
  87970. */
  87971. get: function () {
  87972. return this._deviceOrientationCamera;
  87973. },
  87974. enumerable: true,
  87975. configurable: true
  87976. });
  87977. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87978. /**
  87979. * Based on the current WebVR support, returns the current VR camera used.
  87980. */
  87981. get: function () {
  87982. if (this._webVRready) {
  87983. return this._webVRCamera;
  87984. }
  87985. else {
  87986. return this._scene.activeCamera;
  87987. }
  87988. },
  87989. enumerable: true,
  87990. configurable: true
  87991. });
  87992. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87993. /**
  87994. * The webVRCamera which is used when in VR.
  87995. */
  87996. get: function () {
  87997. return this._webVRCamera;
  87998. },
  87999. enumerable: true,
  88000. configurable: true
  88001. });
  88002. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88003. /**
  88004. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88005. */
  88006. get: function () {
  88007. return this._vrDeviceOrientationCamera;
  88008. },
  88009. enumerable: true,
  88010. configurable: true
  88011. });
  88012. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88013. get: function () {
  88014. var result = this._cameraGazer._teleportationRequestInitiated
  88015. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88016. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88017. return result;
  88018. },
  88019. enumerable: true,
  88020. configurable: true
  88021. });
  88022. // Raised when one of the controller has loaded successfully its associated default mesh
  88023. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88024. if (this.leftController && this.leftController.webVRController == webVRController) {
  88025. if (webVRController.mesh) {
  88026. this.leftController._setLaserPointerParent(webVRController.mesh);
  88027. }
  88028. }
  88029. if (this.rightController && this.rightController.webVRController == webVRController) {
  88030. if (webVRController.mesh) {
  88031. this.rightController._setLaserPointerParent(webVRController.mesh);
  88032. }
  88033. }
  88034. try {
  88035. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88036. }
  88037. catch (err) {
  88038. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88039. }
  88040. };
  88041. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88042. /**
  88043. * Gets a value indicating if we are currently in VR mode.
  88044. */
  88045. get: function () {
  88046. return this._webVRpresenting || this._fullscreenVRpresenting;
  88047. },
  88048. enumerable: true,
  88049. configurable: true
  88050. });
  88051. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88052. var vrDisplay = this._scene.getEngine().getVRDevice();
  88053. if (vrDisplay) {
  88054. var wasPresenting = this._webVRpresenting;
  88055. // A VR display is connected
  88056. this._webVRpresenting = vrDisplay.isPresenting;
  88057. if (wasPresenting && !this._webVRpresenting)
  88058. this.exitVR();
  88059. }
  88060. else {
  88061. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88062. }
  88063. this.updateButtonVisibility();
  88064. };
  88065. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88066. this._webVRsupported = eventArgs.vrSupported;
  88067. this._webVRready = !!eventArgs.vrDisplay;
  88068. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88069. this.updateButtonVisibility();
  88070. };
  88071. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88072. if (this._canvas && !this._useCustomVRButton) {
  88073. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88074. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88075. }
  88076. };
  88077. VRExperienceHelper.prototype.displayVRButton = function () {
  88078. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88079. document.body.appendChild(this._btnVR);
  88080. this._btnVRDisplayed = true;
  88081. }
  88082. };
  88083. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88084. if (!this._btnVR || this._useCustomVRButton) {
  88085. return;
  88086. }
  88087. this._btnVR.className = "babylonVRicon";
  88088. if (this.isInVRMode) {
  88089. this._btnVR.className += " vrdisplaypresenting";
  88090. }
  88091. else {
  88092. if (this._webVRready)
  88093. this._btnVR.className += " vrdisplayready";
  88094. if (this._webVRsupported)
  88095. this._btnVR.className += " vrdisplaysupported";
  88096. if (this._webVRrequesting)
  88097. this._btnVR.className += " vrdisplayrequesting";
  88098. }
  88099. };
  88100. /**
  88101. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88102. * Otherwise, will use the fullscreen API.
  88103. */
  88104. VRExperienceHelper.prototype.enterVR = function () {
  88105. if (this.onEnteringVRObservable) {
  88106. try {
  88107. this.onEnteringVRObservable.notifyObservers(this);
  88108. }
  88109. catch (err) {
  88110. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88111. }
  88112. }
  88113. if (this._scene.activeCamera) {
  88114. this._position = this._scene.activeCamera.position.clone();
  88115. // make sure that we return to the last active camera
  88116. this._existingCamera = this._scene.activeCamera;
  88117. }
  88118. if (this._webVRrequesting)
  88119. return;
  88120. // If WebVR is supported and a headset is connected
  88121. if (this._webVRready) {
  88122. if (!this._webVRpresenting) {
  88123. this._webVRCamera.position = this._position;
  88124. this._scene.activeCamera = this._webVRCamera;
  88125. }
  88126. }
  88127. else if (this._vrDeviceOrientationCamera) {
  88128. this._vrDeviceOrientationCamera.position = this._position;
  88129. if (this._scene.activeCamera) {
  88130. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88131. }
  88132. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88133. this._scene.getEngine().switchFullscreen(true);
  88134. this.updateButtonVisibility();
  88135. }
  88136. if (this._scene.activeCamera && this._canvas) {
  88137. this._scene.activeCamera.attachControl(this._canvas);
  88138. }
  88139. if (this._interactionsEnabled) {
  88140. this._scene.registerBeforeRender(this.beforeRender);
  88141. }
  88142. };
  88143. /**
  88144. * Attempt to exit VR, or fullscreen.
  88145. */
  88146. VRExperienceHelper.prototype.exitVR = function () {
  88147. if (this.onExitingVRObservable) {
  88148. try {
  88149. this.onExitingVRObservable.notifyObservers(this);
  88150. }
  88151. catch (err) {
  88152. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88153. }
  88154. }
  88155. if (this._webVRpresenting) {
  88156. this._scene.getEngine().disableVR();
  88157. }
  88158. if (this._scene.activeCamera) {
  88159. this._position = this._scene.activeCamera.position.clone();
  88160. }
  88161. if (this._deviceOrientationCamera) {
  88162. this._deviceOrientationCamera.position = this._position;
  88163. this._scene.activeCamera = this._deviceOrientationCamera;
  88164. if (this._canvas) {
  88165. this._scene.activeCamera.attachControl(this._canvas);
  88166. }
  88167. }
  88168. else if (this._existingCamera) {
  88169. this._existingCamera.position = this._position;
  88170. this._scene.activeCamera = this._existingCamera;
  88171. }
  88172. this.updateButtonVisibility();
  88173. if (this._interactionsEnabled) {
  88174. this._scene.unregisterBeforeRender(this.beforeRender);
  88175. }
  88176. // resize to update width and height when exiting vr exits fullscreen
  88177. this._scene.getEngine().resize();
  88178. };
  88179. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88180. /**
  88181. * The position of the vr experience helper.
  88182. */
  88183. get: function () {
  88184. return this._position;
  88185. },
  88186. /**
  88187. * Sets the position of the vr experience helper.
  88188. */
  88189. set: function (value) {
  88190. this._position = value;
  88191. if (this._scene.activeCamera) {
  88192. this._scene.activeCamera.position = value;
  88193. }
  88194. },
  88195. enumerable: true,
  88196. configurable: true
  88197. });
  88198. /**
  88199. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88200. */
  88201. VRExperienceHelper.prototype.enableInteractions = function () {
  88202. var _this = this;
  88203. if (!this._interactionsEnabled) {
  88204. this._interactionsRequested = true;
  88205. if (this.leftController) {
  88206. this._enableInteractionOnController(this.leftController);
  88207. }
  88208. if (this.rightController) {
  88209. this._enableInteractionOnController(this.rightController);
  88210. }
  88211. this.raySelectionPredicate = function (mesh) {
  88212. return mesh.isVisible;
  88213. };
  88214. this.meshSelectionPredicate = function (mesh) {
  88215. return true;
  88216. };
  88217. this._raySelectionPredicate = function (mesh) {
  88218. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88219. && mesh.name.indexOf("teleportationTarget") === -1
  88220. && mesh.name.indexOf("torusTeleportation") === -1
  88221. && mesh.name.indexOf("laserPointer") === -1)) {
  88222. return _this.raySelectionPredicate(mesh);
  88223. }
  88224. return false;
  88225. };
  88226. this._interactionsEnabled = true;
  88227. }
  88228. };
  88229. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88230. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88231. if (this._floorMeshesCollection[i].id === mesh.id) {
  88232. return true;
  88233. }
  88234. }
  88235. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88236. return true;
  88237. }
  88238. return false;
  88239. };
  88240. /**
  88241. * Adds a floor mesh to be used for teleportation.
  88242. * @param floorMesh the mesh to be used for teleportation.
  88243. */
  88244. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88245. if (!this._floorMeshesCollection) {
  88246. return;
  88247. }
  88248. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88249. return;
  88250. }
  88251. this._floorMeshesCollection.push(floorMesh);
  88252. };
  88253. /**
  88254. * Removes a floor mesh from being used for teleportation.
  88255. * @param floorMesh the mesh to be removed.
  88256. */
  88257. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88258. if (!this._floorMeshesCollection) {
  88259. return;
  88260. }
  88261. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88262. if (meshIndex !== -1) {
  88263. this._floorMeshesCollection.splice(meshIndex, 1);
  88264. }
  88265. };
  88266. /**
  88267. * Enables interactions and teleportation using the VR controllers and gaze.
  88268. * @param vrTeleportationOptions options to modify teleportation behavior.
  88269. */
  88270. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88271. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88272. if (!this._teleportationInitialized) {
  88273. this._teleportationRequested = true;
  88274. this.enableInteractions();
  88275. if (vrTeleportationOptions.floorMeshName) {
  88276. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88277. }
  88278. if (vrTeleportationOptions.floorMeshes) {
  88279. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88280. }
  88281. if (this.leftController != null) {
  88282. this._enableTeleportationOnController(this.leftController);
  88283. }
  88284. if (this.rightController != null) {
  88285. this._enableTeleportationOnController(this.rightController);
  88286. }
  88287. // Creates an image processing post process for the vignette not relying
  88288. // on the main scene configuration for image processing to reduce setup and spaces
  88289. // (gamma/linear) conflicts.
  88290. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88291. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88292. imageProcessingConfiguration.vignetteEnabled = true;
  88293. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88294. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88295. this._teleportationInitialized = true;
  88296. if (this._isDefaultTeleportationTarget) {
  88297. this._createTeleportationCircles();
  88298. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88299. }
  88300. }
  88301. };
  88302. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88303. var _this = this;
  88304. var controllerMesh = controller.webVRController.mesh;
  88305. if (controllerMesh) {
  88306. controller._interactionsEnabled = true;
  88307. controller._activatePointer();
  88308. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88309. // Enabling / disabling laserPointer
  88310. if (_this._displayLaserPointer && stateObject.value === 1) {
  88311. if (controller._activePointer) {
  88312. controller._deactivatePointer();
  88313. }
  88314. else {
  88315. controller._activatePointer();
  88316. }
  88317. if (_this.displayGaze) {
  88318. controller._gazeTracker.isVisible = controller._activePointer;
  88319. }
  88320. }
  88321. });
  88322. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88323. if (!controller._pointerDownOnMeshAsked) {
  88324. if (stateObject.value > _this._padSensibilityUp) {
  88325. controller._selectionPointerDown();
  88326. }
  88327. }
  88328. else if (stateObject.value < _this._padSensibilityDown) {
  88329. controller._selectionPointerUp();
  88330. }
  88331. });
  88332. }
  88333. };
  88334. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88335. // Dont teleport if another gaze already requested teleportation
  88336. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88337. return;
  88338. }
  88339. if (!gazer._teleportationRequestInitiated) {
  88340. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88341. gazer._activatePointer();
  88342. gazer._teleportationRequestInitiated = true;
  88343. }
  88344. }
  88345. else {
  88346. // Listening to the proper controller values changes to confirm teleportation
  88347. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88348. if (this._teleportActive) {
  88349. this._teleportCamera(this._haloCenter);
  88350. }
  88351. gazer._teleportationRequestInitiated = false;
  88352. }
  88353. }
  88354. };
  88355. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88356. // Only rotate when user is not currently selecting a teleportation location
  88357. if (gazer._teleportationRequestInitiated) {
  88358. return;
  88359. }
  88360. if (!gazer._rotationLeftAsked) {
  88361. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88362. gazer._rotationLeftAsked = true;
  88363. if (this._rotationAllowed) {
  88364. this._rotateCamera(false);
  88365. }
  88366. }
  88367. }
  88368. else {
  88369. if (stateObject.x > -this._padSensibilityDown) {
  88370. gazer._rotationLeftAsked = false;
  88371. }
  88372. }
  88373. if (!gazer._rotationRightAsked) {
  88374. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88375. gazer._rotationRightAsked = true;
  88376. if (this._rotationAllowed) {
  88377. this._rotateCamera(true);
  88378. }
  88379. }
  88380. }
  88381. else {
  88382. if (stateObject.x < this._padSensibilityDown) {
  88383. gazer._rotationRightAsked = false;
  88384. }
  88385. }
  88386. };
  88387. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88388. // Only teleport backwards when user is not currently selecting a teleportation location
  88389. if (gazer._teleportationRequestInitiated) {
  88390. return;
  88391. }
  88392. // Teleport backwards
  88393. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88394. if (!gazer._teleportationBackRequestInitiated) {
  88395. if (!this.currentVRCamera) {
  88396. return;
  88397. }
  88398. // Get rotation and position of the current camera
  88399. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88400. var position = this.currentVRCamera.position;
  88401. // If the camera has device position, use that instead
  88402. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88403. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88404. position = this.currentVRCamera.devicePosition;
  88405. }
  88406. // Get matrix with only the y rotation of the device rotation
  88407. rotation.toEulerAnglesToRef(this._workingVector);
  88408. this._workingVector.z = 0;
  88409. this._workingVector.x = 0;
  88410. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88411. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88412. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88413. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88414. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88415. var ray = new BABYLON.Ray(position, this._workingVector);
  88416. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88417. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88418. this._teleportCamera(hit.pickedPoint);
  88419. }
  88420. gazer._teleportationBackRequestInitiated = true;
  88421. }
  88422. }
  88423. else {
  88424. gazer._teleportationBackRequestInitiated = false;
  88425. }
  88426. };
  88427. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88428. var _this = this;
  88429. var controllerMesh = controller.webVRController.mesh;
  88430. if (controllerMesh) {
  88431. if (!controller._interactionsEnabled) {
  88432. this._enableInteractionOnController(controller);
  88433. }
  88434. controller._interactionsEnabled = true;
  88435. controller._teleportationEnabled = true;
  88436. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88437. controller._dpadPressed = false;
  88438. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88439. controller._dpadPressed = stateObject.pressed;
  88440. if (!controller._dpadPressed) {
  88441. controller._rotationLeftAsked = false;
  88442. controller._rotationRightAsked = false;
  88443. controller._teleportationBackRequestInitiated = false;
  88444. }
  88445. });
  88446. }
  88447. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88448. if (_this.teleportationEnabled) {
  88449. _this._checkTeleportBackwards(stateObject, controller);
  88450. _this._checkTeleportWithRay(stateObject, controller);
  88451. }
  88452. _this._checkRotate(stateObject, controller);
  88453. });
  88454. }
  88455. };
  88456. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88457. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88458. this._teleportationTarget.isPickable = false;
  88459. var length = 512;
  88460. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88461. dynamicTexture.hasAlpha = true;
  88462. var context = dynamicTexture.getContext();
  88463. var centerX = length / 2;
  88464. var centerY = length / 2;
  88465. var radius = 200;
  88466. context.beginPath();
  88467. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88468. context.fillStyle = this._teleportationFillColor;
  88469. context.fill();
  88470. context.lineWidth = 10;
  88471. context.strokeStyle = this._teleportationBorderColor;
  88472. context.stroke();
  88473. context.closePath();
  88474. dynamicTexture.update();
  88475. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88476. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88477. this._teleportationTarget.material = teleportationCircleMaterial;
  88478. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88479. torus.isPickable = false;
  88480. torus.parent = this._teleportationTarget;
  88481. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88482. var keys = [];
  88483. keys.push({
  88484. frame: 0,
  88485. value: 0
  88486. });
  88487. keys.push({
  88488. frame: 30,
  88489. value: 0.4
  88490. });
  88491. keys.push({
  88492. frame: 60,
  88493. value: 0
  88494. });
  88495. animationInnerCircle.setKeys(keys);
  88496. var easingFunction = new BABYLON.SineEase();
  88497. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88498. animationInnerCircle.setEasingFunction(easingFunction);
  88499. torus.animations = [];
  88500. torus.animations.push(animationInnerCircle);
  88501. this._scene.beginAnimation(torus, 0, 60, true);
  88502. this._hideTeleportationTarget();
  88503. };
  88504. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88505. this._teleportActive = true;
  88506. if (this._teleportationInitialized) {
  88507. this._teleportationTarget.isVisible = true;
  88508. if (this._isDefaultTeleportationTarget) {
  88509. this._teleportationTarget.getChildren()[0].isVisible = true;
  88510. }
  88511. }
  88512. };
  88513. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88514. this._teleportActive = false;
  88515. if (this._teleportationInitialized) {
  88516. this._teleportationTarget.isVisible = false;
  88517. if (this._isDefaultTeleportationTarget) {
  88518. this._teleportationTarget.getChildren()[0].isVisible = false;
  88519. }
  88520. }
  88521. };
  88522. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88523. var _this = this;
  88524. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88525. return;
  88526. }
  88527. if (right) {
  88528. this._rotationAngle++;
  88529. }
  88530. else {
  88531. this._rotationAngle--;
  88532. }
  88533. this.currentVRCamera.animations = [];
  88534. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88535. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88536. var animationRotationKeys = [];
  88537. animationRotationKeys.push({
  88538. frame: 0,
  88539. value: this.currentVRCamera.rotationQuaternion
  88540. });
  88541. animationRotationKeys.push({
  88542. frame: 6,
  88543. value: target
  88544. });
  88545. animationRotation.setKeys(animationRotationKeys);
  88546. animationRotation.setEasingFunction(this._circleEase);
  88547. this.currentVRCamera.animations.push(animationRotation);
  88548. this._postProcessMove.animations = [];
  88549. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88550. var vignetteWeightKeys = [];
  88551. vignetteWeightKeys.push({
  88552. frame: 0,
  88553. value: 0
  88554. });
  88555. vignetteWeightKeys.push({
  88556. frame: 3,
  88557. value: 4
  88558. });
  88559. vignetteWeightKeys.push({
  88560. frame: 6,
  88561. value: 0
  88562. });
  88563. animationPP.setKeys(vignetteWeightKeys);
  88564. animationPP.setEasingFunction(this._circleEase);
  88565. this._postProcessMove.animations.push(animationPP);
  88566. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88567. var vignetteStretchKeys = [];
  88568. vignetteStretchKeys.push({
  88569. frame: 0,
  88570. value: 0
  88571. });
  88572. vignetteStretchKeys.push({
  88573. frame: 3,
  88574. value: 10
  88575. });
  88576. vignetteStretchKeys.push({
  88577. frame: 6,
  88578. value: 0
  88579. });
  88580. animationPP2.setKeys(vignetteStretchKeys);
  88581. animationPP2.setEasingFunction(this._circleEase);
  88582. this._postProcessMove.animations.push(animationPP2);
  88583. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88584. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88585. this._postProcessMove.samples = 4;
  88586. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88587. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88588. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88589. });
  88590. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88591. };
  88592. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88593. if (hit.pickedPoint) {
  88594. if (gazer._teleportationRequestInitiated) {
  88595. this._displayTeleportationTarget();
  88596. this._haloCenter.copyFrom(hit.pickedPoint);
  88597. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88598. }
  88599. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88600. if (pickNormal) {
  88601. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88602. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88603. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88604. }
  88605. this._teleportationTarget.position.y += 0.1;
  88606. }
  88607. };
  88608. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88609. var _this = this;
  88610. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88611. return;
  88612. }
  88613. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88614. // offset of the headset from the anchor.
  88615. if (this.webVRCamera.leftCamera) {
  88616. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88617. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88618. location.subtractToRef(this._workingVector, this._workingVector);
  88619. }
  88620. else {
  88621. this._workingVector.copyFrom(location);
  88622. }
  88623. // Add height to account for user's height offset
  88624. if (this.isInVRMode) {
  88625. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88626. }
  88627. else {
  88628. this._workingVector.y += this._defaultHeight;
  88629. }
  88630. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88631. // Create animation from the camera's position to the new location
  88632. this.currentVRCamera.animations = [];
  88633. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88634. var animationCameraTeleportationKeys = [{
  88635. frame: 0,
  88636. value: this.currentVRCamera.position
  88637. },
  88638. {
  88639. frame: 11,
  88640. value: this._workingVector
  88641. }
  88642. ];
  88643. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88644. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88645. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88646. this._postProcessMove.animations = [];
  88647. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88648. var vignetteWeightKeys = [];
  88649. vignetteWeightKeys.push({
  88650. frame: 0,
  88651. value: 0
  88652. });
  88653. vignetteWeightKeys.push({
  88654. frame: 5,
  88655. value: 8
  88656. });
  88657. vignetteWeightKeys.push({
  88658. frame: 11,
  88659. value: 0
  88660. });
  88661. animationPP.setKeys(vignetteWeightKeys);
  88662. this._postProcessMove.animations.push(animationPP);
  88663. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88664. var vignetteStretchKeys = [];
  88665. vignetteStretchKeys.push({
  88666. frame: 0,
  88667. value: 0
  88668. });
  88669. vignetteStretchKeys.push({
  88670. frame: 5,
  88671. value: 10
  88672. });
  88673. vignetteStretchKeys.push({
  88674. frame: 11,
  88675. value: 0
  88676. });
  88677. animationPP2.setKeys(vignetteStretchKeys);
  88678. this._postProcessMove.animations.push(animationPP2);
  88679. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88680. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88681. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88682. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88683. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88684. });
  88685. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88686. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88687. });
  88688. this._hideTeleportationTarget();
  88689. };
  88690. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88691. if (normal) {
  88692. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88693. if (angle < Math.PI / 2) {
  88694. normal.scaleInPlace(-1);
  88695. }
  88696. }
  88697. return normal;
  88698. };
  88699. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88700. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88701. return;
  88702. }
  88703. var ray = gazer._getForwardRay(this._rayLength);
  88704. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88705. // Moving the gazeTracker on the mesh face targetted
  88706. if (hit && hit.pickedPoint) {
  88707. if (this._displayGaze) {
  88708. var multiplier = 1;
  88709. gazer._gazeTracker.isVisible = true;
  88710. if (gazer._isActionableMesh) {
  88711. multiplier = 3;
  88712. }
  88713. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88714. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88715. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88716. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88717. // To avoid z-fighting
  88718. var deltaFighting = 0.002;
  88719. if (pickNormal) {
  88720. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88721. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88722. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88723. }
  88724. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88725. if (gazer._gazeTracker.position.x < 0) {
  88726. gazer._gazeTracker.position.x += deltaFighting;
  88727. }
  88728. else {
  88729. gazer._gazeTracker.position.x -= deltaFighting;
  88730. }
  88731. if (gazer._gazeTracker.position.y < 0) {
  88732. gazer._gazeTracker.position.y += deltaFighting;
  88733. }
  88734. else {
  88735. gazer._gazeTracker.position.y -= deltaFighting;
  88736. }
  88737. if (gazer._gazeTracker.position.z < 0) {
  88738. gazer._gazeTracker.position.z += deltaFighting;
  88739. }
  88740. else {
  88741. gazer._gazeTracker.position.z -= deltaFighting;
  88742. }
  88743. }
  88744. // Changing the size of the laser pointer based on the distance from the targetted point
  88745. gazer._updatePointerDistance(hit.distance);
  88746. }
  88747. else {
  88748. gazer._updatePointerDistance();
  88749. gazer._gazeTracker.isVisible = false;
  88750. }
  88751. if (hit && hit.pickedMesh) {
  88752. gazer._currentHit = hit;
  88753. if (gazer._pointerDownOnMeshAsked) {
  88754. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88755. }
  88756. // The object selected is the floor, we're in a teleportation scenario
  88757. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88758. // Moving the teleportation area to this targetted point
  88759. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88760. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88761. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88762. }
  88763. gazer._currentMeshSelected = null;
  88764. if (gazer._teleportationRequestInitiated) {
  88765. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88766. }
  88767. return;
  88768. }
  88769. // If not, we're in a selection scenario
  88770. //this._teleportationAllowed = false;
  88771. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88772. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88773. this.onNewMeshPicked.notifyObservers(hit);
  88774. gazer._currentMeshSelected = hit.pickedMesh;
  88775. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88776. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88777. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88778. gazer._isActionableMesh = true;
  88779. }
  88780. else {
  88781. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88782. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88783. gazer._isActionableMesh = false;
  88784. }
  88785. try {
  88786. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88787. }
  88788. catch (err) {
  88789. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88790. }
  88791. }
  88792. else {
  88793. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88794. gazer._currentMeshSelected = null;
  88795. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88796. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88797. }
  88798. }
  88799. }
  88800. else {
  88801. gazer._currentHit = null;
  88802. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88803. gazer._currentMeshSelected = null;
  88804. //this._teleportationAllowed = false;
  88805. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88806. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88807. }
  88808. };
  88809. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88810. if (mesh) {
  88811. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88812. }
  88813. };
  88814. /**
  88815. * Sets the color of the laser ray from the vr controllers.
  88816. * @param color new color for the ray.
  88817. */
  88818. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88819. if (this.leftController) {
  88820. this.leftController._setLaserPointerColor(color);
  88821. }
  88822. if (this.rightController) {
  88823. this.rightController._setLaserPointerColor(color);
  88824. }
  88825. };
  88826. /**
  88827. * Sets the color of the ray from the vr headsets gaze.
  88828. * @param color new color for the ray.
  88829. */
  88830. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88831. if (!this._cameraGazer._gazeTracker.material) {
  88832. return;
  88833. }
  88834. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88835. if (this.leftController) {
  88836. this.leftController._gazeTracker.material.emissiveColor = color;
  88837. }
  88838. if (this.rightController) {
  88839. this.rightController._gazeTracker.material.emissiveColor = color;
  88840. }
  88841. };
  88842. /**
  88843. * Exits VR and disposes of the vr experience helper
  88844. */
  88845. VRExperienceHelper.prototype.dispose = function () {
  88846. if (this.isInVRMode) {
  88847. this.exitVR();
  88848. }
  88849. if (this._postProcessMove) {
  88850. this._postProcessMove.dispose();
  88851. }
  88852. if (this._webVRCamera) {
  88853. this._webVRCamera.dispose();
  88854. }
  88855. if (this._vrDeviceOrientationCamera) {
  88856. this._vrDeviceOrientationCamera.dispose();
  88857. }
  88858. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88859. document.body.removeChild(this._btnVR);
  88860. }
  88861. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88862. this._deviceOrientationCamera.dispose();
  88863. }
  88864. if (this._cameraGazer) {
  88865. this._cameraGazer.dispose();
  88866. }
  88867. if (this.leftController) {
  88868. this.leftController.dispose();
  88869. }
  88870. if (this.rightController) {
  88871. this.rightController.dispose();
  88872. }
  88873. if (this._teleportationTarget) {
  88874. this._teleportationTarget.dispose();
  88875. }
  88876. this._floorMeshesCollection = [];
  88877. document.removeEventListener("keydown", this._onKeyDown);
  88878. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88879. window.removeEventListener("resize", this._onResize);
  88880. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88881. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88882. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88883. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88884. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88885. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88886. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88887. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88888. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88889. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88890. this._scene.unregisterBeforeRender(this.beforeRender);
  88891. };
  88892. /**
  88893. * Gets the name of the VRExperienceHelper class
  88894. * @returns "VRExperienceHelper"
  88895. */
  88896. VRExperienceHelper.prototype.getClassName = function () {
  88897. return "VRExperienceHelper";
  88898. };
  88899. return VRExperienceHelper;
  88900. }());
  88901. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88902. })(BABYLON || (BABYLON = {}));
  88903. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88904. // Mainly based on these 2 articles :
  88905. // 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
  88906. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88907. var BABYLON;
  88908. (function (BABYLON) {
  88909. /**
  88910. * Defines the potential axis of a Joystick
  88911. */
  88912. var JoystickAxis;
  88913. (function (JoystickAxis) {
  88914. /** X axis */
  88915. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88916. /** Y axis */
  88917. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88918. /** Z axis */
  88919. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88920. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88921. /**
  88922. * Class used to define virtual joystick (used in touch mode)
  88923. */
  88924. var VirtualJoystick = /** @class */ (function () {
  88925. /**
  88926. * Creates a new virtual joystick
  88927. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88928. */
  88929. function VirtualJoystick(leftJoystick) {
  88930. var _this = this;
  88931. if (leftJoystick) {
  88932. this._leftJoystick = true;
  88933. }
  88934. else {
  88935. this._leftJoystick = false;
  88936. }
  88937. VirtualJoystick._globalJoystickIndex++;
  88938. // By default left & right arrow keys are moving the X
  88939. // and up & down keys are moving the Y
  88940. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88941. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88942. this.reverseLeftRight = false;
  88943. this.reverseUpDown = false;
  88944. // collections of pointers
  88945. this._touches = new BABYLON.StringDictionary();
  88946. this.deltaPosition = BABYLON.Vector3.Zero();
  88947. this._joystickSensibility = 25;
  88948. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88949. this._onResize = function (evt) {
  88950. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88951. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88952. if (VirtualJoystick.vjCanvas) {
  88953. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88954. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88955. }
  88956. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88957. };
  88958. // injecting a canvas element on top of the canvas 3D game
  88959. if (!VirtualJoystick.vjCanvas) {
  88960. window.addEventListener("resize", this._onResize, false);
  88961. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88962. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88963. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88964. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88965. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88966. VirtualJoystick.vjCanvas.style.width = "100%";
  88967. VirtualJoystick.vjCanvas.style.height = "100%";
  88968. VirtualJoystick.vjCanvas.style.position = "absolute";
  88969. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88970. VirtualJoystick.vjCanvas.style.top = "0px";
  88971. VirtualJoystick.vjCanvas.style.left = "0px";
  88972. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88973. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88974. // Support for jQuery PEP polyfill
  88975. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88976. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88977. if (!context) {
  88978. throw new Error("Unable to create canvas for virtual joystick");
  88979. }
  88980. VirtualJoystick.vjCanvasContext = context;
  88981. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88982. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88983. document.body.appendChild(VirtualJoystick.vjCanvas);
  88984. }
  88985. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88986. this.pressed = false;
  88987. // default joystick color
  88988. this._joystickColor = "cyan";
  88989. this._joystickPointerID = -1;
  88990. // current joystick position
  88991. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88992. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88993. // origin joystick position
  88994. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88995. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88996. this._onPointerDownHandlerRef = function (evt) {
  88997. _this._onPointerDown(evt);
  88998. };
  88999. this._onPointerMoveHandlerRef = function (evt) {
  89000. _this._onPointerMove(evt);
  89001. };
  89002. this._onPointerUpHandlerRef = function (evt) {
  89003. _this._onPointerUp(evt);
  89004. };
  89005. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89006. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89007. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89008. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89009. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89010. evt.preventDefault(); // Disables system menu
  89011. }, false);
  89012. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89013. }
  89014. /**
  89015. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89016. * @param newJoystickSensibility defines the new sensibility
  89017. */
  89018. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89019. this._joystickSensibility = newJoystickSensibility;
  89020. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89021. };
  89022. VirtualJoystick.prototype._onPointerDown = function (e) {
  89023. var positionOnScreenCondition;
  89024. e.preventDefault();
  89025. if (this._leftJoystick === true) {
  89026. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89027. }
  89028. else {
  89029. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89030. }
  89031. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89032. // First contact will be dedicated to the virtual joystick
  89033. this._joystickPointerID = e.pointerId;
  89034. this._joystickPointerStartPos.x = e.clientX;
  89035. this._joystickPointerStartPos.y = e.clientY;
  89036. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89037. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89038. this._deltaJoystickVector.x = 0;
  89039. this._deltaJoystickVector.y = 0;
  89040. this.pressed = true;
  89041. this._touches.add(e.pointerId.toString(), e);
  89042. }
  89043. else {
  89044. // You can only trigger the action buttons with a joystick declared
  89045. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89046. this._action();
  89047. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89048. }
  89049. }
  89050. };
  89051. VirtualJoystick.prototype._onPointerMove = function (e) {
  89052. // If the current pointer is the one associated to the joystick (first touch contact)
  89053. if (this._joystickPointerID == e.pointerId) {
  89054. this._joystickPointerPos.x = e.clientX;
  89055. this._joystickPointerPos.y = e.clientY;
  89056. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89057. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89058. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89059. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89060. switch (this._axisTargetedByLeftAndRight) {
  89061. case JoystickAxis.X:
  89062. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89063. break;
  89064. case JoystickAxis.Y:
  89065. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89066. break;
  89067. case JoystickAxis.Z:
  89068. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89069. break;
  89070. }
  89071. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89072. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89073. switch (this._axisTargetedByUpAndDown) {
  89074. case JoystickAxis.X:
  89075. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89076. break;
  89077. case JoystickAxis.Y:
  89078. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89079. break;
  89080. case JoystickAxis.Z:
  89081. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89082. break;
  89083. }
  89084. }
  89085. else {
  89086. var data = this._touches.get(e.pointerId.toString());
  89087. if (data) {
  89088. data.x = e.clientX;
  89089. data.y = e.clientY;
  89090. }
  89091. }
  89092. };
  89093. VirtualJoystick.prototype._onPointerUp = function (e) {
  89094. if (this._joystickPointerID == e.pointerId) {
  89095. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89096. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89097. this._joystickPointerID = -1;
  89098. this.pressed = false;
  89099. }
  89100. else {
  89101. var touch = this._touches.get(e.pointerId.toString());
  89102. if (touch) {
  89103. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89104. }
  89105. }
  89106. this._deltaJoystickVector.x = 0;
  89107. this._deltaJoystickVector.y = 0;
  89108. this._touches.remove(e.pointerId.toString());
  89109. };
  89110. /**
  89111. * Change the color of the virtual joystick
  89112. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89113. */
  89114. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89115. this._joystickColor = newColor;
  89116. };
  89117. /**
  89118. * Defines a callback to call when the joystick is touched
  89119. * @param action defines the callback
  89120. */
  89121. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89122. this._action = action;
  89123. };
  89124. /**
  89125. * Defines which axis you'd like to control for left & right
  89126. * @param axis defines the axis to use
  89127. */
  89128. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89129. switch (axis) {
  89130. case JoystickAxis.X:
  89131. case JoystickAxis.Y:
  89132. case JoystickAxis.Z:
  89133. this._axisTargetedByLeftAndRight = axis;
  89134. break;
  89135. default:
  89136. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89137. break;
  89138. }
  89139. };
  89140. /**
  89141. * Defines which axis you'd like to control for up & down
  89142. * @param axis defines the axis to use
  89143. */
  89144. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89145. switch (axis) {
  89146. case JoystickAxis.X:
  89147. case JoystickAxis.Y:
  89148. case JoystickAxis.Z:
  89149. this._axisTargetedByUpAndDown = axis;
  89150. break;
  89151. default:
  89152. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89153. break;
  89154. }
  89155. };
  89156. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89157. var _this = this;
  89158. if (this.pressed) {
  89159. this._touches.forEach(function (key, touch) {
  89160. if (touch.pointerId === _this._joystickPointerID) {
  89161. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89162. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89163. VirtualJoystick.vjCanvasContext.beginPath();
  89164. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89165. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89166. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89167. VirtualJoystick.vjCanvasContext.stroke();
  89168. VirtualJoystick.vjCanvasContext.closePath();
  89169. VirtualJoystick.vjCanvasContext.beginPath();
  89170. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89171. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89172. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89173. VirtualJoystick.vjCanvasContext.stroke();
  89174. VirtualJoystick.vjCanvasContext.closePath();
  89175. VirtualJoystick.vjCanvasContext.beginPath();
  89176. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89177. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89178. VirtualJoystick.vjCanvasContext.stroke();
  89179. VirtualJoystick.vjCanvasContext.closePath();
  89180. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89181. }
  89182. else {
  89183. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89184. VirtualJoystick.vjCanvasContext.beginPath();
  89185. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89186. VirtualJoystick.vjCanvasContext.beginPath();
  89187. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89188. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89189. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89190. VirtualJoystick.vjCanvasContext.stroke();
  89191. VirtualJoystick.vjCanvasContext.closePath();
  89192. touch.prevX = touch.x;
  89193. touch.prevY = touch.y;
  89194. }
  89195. ;
  89196. });
  89197. }
  89198. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89199. };
  89200. /**
  89201. * Release internal HTML canvas
  89202. */
  89203. VirtualJoystick.prototype.releaseCanvas = function () {
  89204. if (VirtualJoystick.vjCanvas) {
  89205. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89206. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89207. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89208. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89209. window.removeEventListener("resize", this._onResize);
  89210. document.body.removeChild(VirtualJoystick.vjCanvas);
  89211. VirtualJoystick.vjCanvas = null;
  89212. }
  89213. };
  89214. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89215. VirtualJoystick._globalJoystickIndex = 0;
  89216. return VirtualJoystick;
  89217. }());
  89218. BABYLON.VirtualJoystick = VirtualJoystick;
  89219. })(BABYLON || (BABYLON = {}));
  89220. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89221. var BABYLON;
  89222. (function (BABYLON) {
  89223. // We're mainly based on the logic defined into the FreeCamera code
  89224. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89225. __extends(VirtualJoysticksCamera, _super);
  89226. function VirtualJoysticksCamera(name, position, scene) {
  89227. var _this = _super.call(this, name, position, scene) || this;
  89228. _this.inputs.addVirtualJoystick();
  89229. return _this;
  89230. }
  89231. VirtualJoysticksCamera.prototype.getClassName = function () {
  89232. return "VirtualJoysticksCamera";
  89233. };
  89234. return VirtualJoysticksCamera;
  89235. }(BABYLON.FreeCamera));
  89236. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89237. })(BABYLON || (BABYLON = {}));
  89238. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89239. var BABYLON;
  89240. (function (BABYLON) {
  89241. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89242. function FreeCameraVirtualJoystickInput() {
  89243. }
  89244. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89245. return this._leftjoystick;
  89246. };
  89247. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89248. return this._rightjoystick;
  89249. };
  89250. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89251. if (this._leftjoystick) {
  89252. var camera = this.camera;
  89253. var speed = camera._computeLocalCameraSpeed() * 50;
  89254. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89255. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89256. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89257. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89258. if (!this._leftjoystick.pressed) {
  89259. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89260. }
  89261. if (!this._rightjoystick.pressed) {
  89262. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89263. }
  89264. }
  89265. };
  89266. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89267. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89268. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89269. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89270. this._leftjoystick.setJoystickSensibility(0.15);
  89271. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89272. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89273. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89274. this._rightjoystick.reverseUpDown = true;
  89275. this._rightjoystick.setJoystickSensibility(0.05);
  89276. this._rightjoystick.setJoystickColor("yellow");
  89277. };
  89278. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89279. this._leftjoystick.releaseCanvas();
  89280. this._rightjoystick.releaseCanvas();
  89281. };
  89282. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89283. return "FreeCameraVirtualJoystickInput";
  89284. };
  89285. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89286. return "virtualJoystick";
  89287. };
  89288. return FreeCameraVirtualJoystickInput;
  89289. }());
  89290. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89291. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89292. })(BABYLON || (BABYLON = {}));
  89293. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89294. var BABYLON;
  89295. (function (BABYLON) {
  89296. var SimplificationSettings = /** @class */ (function () {
  89297. function SimplificationSettings(quality, distance, optimizeMesh) {
  89298. this.quality = quality;
  89299. this.distance = distance;
  89300. this.optimizeMesh = optimizeMesh;
  89301. }
  89302. return SimplificationSettings;
  89303. }());
  89304. BABYLON.SimplificationSettings = SimplificationSettings;
  89305. var SimplificationQueue = /** @class */ (function () {
  89306. function SimplificationQueue() {
  89307. this.running = false;
  89308. this._simplificationArray = [];
  89309. }
  89310. SimplificationQueue.prototype.addTask = function (task) {
  89311. this._simplificationArray.push(task);
  89312. };
  89313. SimplificationQueue.prototype.executeNext = function () {
  89314. var task = this._simplificationArray.pop();
  89315. if (task) {
  89316. this.running = true;
  89317. this.runSimplification(task);
  89318. }
  89319. else {
  89320. this.running = false;
  89321. }
  89322. };
  89323. SimplificationQueue.prototype.runSimplification = function (task) {
  89324. var _this = this;
  89325. if (task.parallelProcessing) {
  89326. //parallel simplifier
  89327. task.settings.forEach(function (setting) {
  89328. var simplifier = _this.getSimplifier(task);
  89329. simplifier.simplify(setting, function (newMesh) {
  89330. task.mesh.addLODLevel(setting.distance, newMesh);
  89331. newMesh.isVisible = true;
  89332. //check if it is the last
  89333. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89334. //all done, run the success callback.
  89335. task.successCallback();
  89336. }
  89337. _this.executeNext();
  89338. });
  89339. });
  89340. }
  89341. else {
  89342. //single simplifier.
  89343. var simplifier = this.getSimplifier(task);
  89344. var runDecimation = function (setting, callback) {
  89345. simplifier.simplify(setting, function (newMesh) {
  89346. task.mesh.addLODLevel(setting.distance, newMesh);
  89347. newMesh.isVisible = true;
  89348. //run the next quality level
  89349. callback();
  89350. });
  89351. };
  89352. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89353. runDecimation(task.settings[loop.index], function () {
  89354. loop.executeNext();
  89355. });
  89356. }, function () {
  89357. //execution ended, run the success callback.
  89358. if (task.successCallback) {
  89359. task.successCallback();
  89360. }
  89361. _this.executeNext();
  89362. });
  89363. }
  89364. };
  89365. SimplificationQueue.prototype.getSimplifier = function (task) {
  89366. switch (task.simplificationType) {
  89367. case SimplificationType.QUADRATIC:
  89368. default:
  89369. return new QuadraticErrorSimplification(task.mesh);
  89370. }
  89371. };
  89372. return SimplificationQueue;
  89373. }());
  89374. BABYLON.SimplificationQueue = SimplificationQueue;
  89375. /**
  89376. * The implemented types of simplification
  89377. * At the moment only Quadratic Error Decimation is implemented
  89378. */
  89379. var SimplificationType;
  89380. (function (SimplificationType) {
  89381. /** Quadratic error decimation */
  89382. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89383. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89384. var DecimationTriangle = /** @class */ (function () {
  89385. function DecimationTriangle(vertices) {
  89386. this.vertices = vertices;
  89387. this.error = new Array(4);
  89388. this.deleted = false;
  89389. this.isDirty = false;
  89390. this.deletePending = false;
  89391. this.borderFactor = 0;
  89392. }
  89393. return DecimationTriangle;
  89394. }());
  89395. BABYLON.DecimationTriangle = DecimationTriangle;
  89396. var DecimationVertex = /** @class */ (function () {
  89397. function DecimationVertex(position, id) {
  89398. this.position = position;
  89399. this.id = id;
  89400. this.isBorder = true;
  89401. this.q = new QuadraticMatrix();
  89402. this.triangleCount = 0;
  89403. this.triangleStart = 0;
  89404. this.originalOffsets = [];
  89405. }
  89406. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89407. this.position.copyFrom(newPosition);
  89408. };
  89409. return DecimationVertex;
  89410. }());
  89411. BABYLON.DecimationVertex = DecimationVertex;
  89412. var QuadraticMatrix = /** @class */ (function () {
  89413. function QuadraticMatrix(data) {
  89414. this.data = new Array(10);
  89415. for (var i = 0; i < 10; ++i) {
  89416. if (data && data[i]) {
  89417. this.data[i] = data[i];
  89418. }
  89419. else {
  89420. this.data[i] = 0;
  89421. }
  89422. }
  89423. }
  89424. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89425. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89426. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89427. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89428. return det;
  89429. };
  89430. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89431. for (var i = 0; i < 10; ++i) {
  89432. this.data[i] += matrix.data[i];
  89433. }
  89434. };
  89435. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89436. for (var i = 0; i < 10; ++i) {
  89437. this.data[i] += data[i];
  89438. }
  89439. };
  89440. QuadraticMatrix.prototype.add = function (matrix) {
  89441. var m = new QuadraticMatrix();
  89442. for (var i = 0; i < 10; ++i) {
  89443. m.data[i] = this.data[i] + matrix.data[i];
  89444. }
  89445. return m;
  89446. };
  89447. QuadraticMatrix.FromData = function (a, b, c, d) {
  89448. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89449. };
  89450. //returning an array to avoid garbage collection
  89451. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89452. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89453. };
  89454. return QuadraticMatrix;
  89455. }());
  89456. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89457. var Reference = /** @class */ (function () {
  89458. function Reference(vertexId, triangleId) {
  89459. this.vertexId = vertexId;
  89460. this.triangleId = triangleId;
  89461. }
  89462. return Reference;
  89463. }());
  89464. BABYLON.Reference = Reference;
  89465. /**
  89466. * An implementation of the Quadratic Error simplification algorithm.
  89467. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89468. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89469. * @author RaananW
  89470. */
  89471. var QuadraticErrorSimplification = /** @class */ (function () {
  89472. function QuadraticErrorSimplification(_mesh) {
  89473. this._mesh = _mesh;
  89474. this.syncIterations = 5000;
  89475. this.aggressiveness = 7;
  89476. this.decimationIterations = 100;
  89477. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89478. }
  89479. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89480. var _this = this;
  89481. this.initDecimatedMesh();
  89482. //iterating through the submeshes array, one after the other.
  89483. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89484. _this.initWithMesh(loop.index, function () {
  89485. _this.runDecimation(settings, loop.index, function () {
  89486. loop.executeNext();
  89487. });
  89488. }, settings.optimizeMesh);
  89489. }, function () {
  89490. setTimeout(function () {
  89491. successCallback(_this._reconstructedMesh);
  89492. }, 0);
  89493. });
  89494. };
  89495. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89496. var _this = this;
  89497. var targetCount = ~~(this.triangles.length * settings.quality);
  89498. var deletedTriangles = 0;
  89499. var triangleCount = this.triangles.length;
  89500. var iterationFunction = function (iteration, callback) {
  89501. setTimeout(function () {
  89502. if (iteration % 5 === 0) {
  89503. _this.updateMesh(iteration === 0);
  89504. }
  89505. for (var i = 0; i < _this.triangles.length; ++i) {
  89506. _this.triangles[i].isDirty = false;
  89507. }
  89508. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89509. var trianglesIterator = function (i) {
  89510. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89511. var t = _this.triangles[tIdx];
  89512. if (!t)
  89513. return;
  89514. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89515. return;
  89516. }
  89517. for (var j = 0; j < 3; ++j) {
  89518. if (t.error[j] < threshold) {
  89519. var deleted0 = [];
  89520. var deleted1 = [];
  89521. var v0 = t.vertices[j];
  89522. var v1 = t.vertices[(j + 1) % 3];
  89523. if (v0.isBorder || v1.isBorder)
  89524. continue;
  89525. var p = BABYLON.Vector3.Zero();
  89526. var n = BABYLON.Vector3.Zero();
  89527. var uv = BABYLON.Vector2.Zero();
  89528. var color = new BABYLON.Color4(0, 0, 0, 1);
  89529. _this.calculateError(v0, v1, p, n, uv, color);
  89530. var delTr = new Array();
  89531. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89532. continue;
  89533. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89534. continue;
  89535. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89536. continue;
  89537. var uniqueArray = new Array();
  89538. delTr.forEach(function (deletedT) {
  89539. if (uniqueArray.indexOf(deletedT) === -1) {
  89540. deletedT.deletePending = true;
  89541. uniqueArray.push(deletedT);
  89542. }
  89543. });
  89544. if (uniqueArray.length % 2 !== 0) {
  89545. continue;
  89546. }
  89547. v0.q = v1.q.add(v0.q);
  89548. v0.updatePosition(p);
  89549. var tStart = _this.references.length;
  89550. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89551. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89552. var tCount = _this.references.length - tStart;
  89553. if (tCount <= v0.triangleCount) {
  89554. if (tCount) {
  89555. for (var c = 0; c < tCount; c++) {
  89556. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89557. }
  89558. }
  89559. }
  89560. else {
  89561. v0.triangleStart = tStart;
  89562. }
  89563. v0.triangleCount = tCount;
  89564. break;
  89565. }
  89566. }
  89567. };
  89568. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89569. }, 0);
  89570. };
  89571. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89572. if (triangleCount - deletedTriangles <= targetCount)
  89573. loop.breakLoop();
  89574. else {
  89575. iterationFunction(loop.index, function () {
  89576. loop.executeNext();
  89577. });
  89578. }
  89579. }, function () {
  89580. setTimeout(function () {
  89581. //reconstruct this part of the mesh
  89582. _this.reconstructMesh(submeshIndex);
  89583. successCallback();
  89584. }, 0);
  89585. });
  89586. };
  89587. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89588. var _this = this;
  89589. this.vertices = [];
  89590. this.triangles = [];
  89591. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89592. var indices = this._mesh.getIndices();
  89593. var submesh = this._mesh.subMeshes[submeshIndex];
  89594. var findInVertices = function (positionToSearch) {
  89595. if (optimizeMesh) {
  89596. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89597. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89598. return _this.vertices[ii];
  89599. }
  89600. }
  89601. }
  89602. return null;
  89603. };
  89604. var vertexReferences = [];
  89605. var vertexInit = function (i) {
  89606. if (!positionData) {
  89607. return;
  89608. }
  89609. var offset = i + submesh.verticesStart;
  89610. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89611. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89612. vertex.originalOffsets.push(offset);
  89613. if (vertex.id === _this.vertices.length) {
  89614. _this.vertices.push(vertex);
  89615. }
  89616. vertexReferences.push(vertex.id);
  89617. };
  89618. //var totalVertices = mesh.getTotalVertices();
  89619. var totalVertices = submesh.verticesCount;
  89620. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89621. var indicesInit = function (i) {
  89622. if (!indices) {
  89623. return;
  89624. }
  89625. var offset = (submesh.indexStart / 3) + i;
  89626. var pos = (offset * 3);
  89627. var i0 = indices[pos + 0];
  89628. var i1 = indices[pos + 1];
  89629. var i2 = indices[pos + 2];
  89630. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89631. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89632. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89633. var triangle = new DecimationTriangle([v0, v1, v2]);
  89634. triangle.originalOffset = pos;
  89635. _this.triangles.push(triangle);
  89636. };
  89637. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89638. _this.init(callback);
  89639. });
  89640. });
  89641. };
  89642. QuadraticErrorSimplification.prototype.init = function (callback) {
  89643. var _this = this;
  89644. var triangleInit1 = function (i) {
  89645. var t = _this.triangles[i];
  89646. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89647. for (var j = 0; j < 3; j++) {
  89648. 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))));
  89649. }
  89650. };
  89651. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89652. var triangleInit2 = function (i) {
  89653. var t = _this.triangles[i];
  89654. for (var j = 0; j < 3; ++j) {
  89655. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89656. }
  89657. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89658. };
  89659. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89660. callback();
  89661. });
  89662. });
  89663. };
  89664. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89665. var newTriangles = [];
  89666. var i;
  89667. for (i = 0; i < this.vertices.length; ++i) {
  89668. this.vertices[i].triangleCount = 0;
  89669. }
  89670. var t;
  89671. var j;
  89672. for (i = 0; i < this.triangles.length; ++i) {
  89673. if (!this.triangles[i].deleted) {
  89674. t = this.triangles[i];
  89675. for (j = 0; j < 3; ++j) {
  89676. t.vertices[j].triangleCount = 1;
  89677. }
  89678. newTriangles.push(t);
  89679. }
  89680. }
  89681. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89682. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89683. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89684. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89685. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89686. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89687. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89688. var vertexCount = 0;
  89689. for (i = 0; i < this.vertices.length; ++i) {
  89690. var vertex = this.vertices[i];
  89691. vertex.id = vertexCount;
  89692. if (vertex.triangleCount) {
  89693. vertex.originalOffsets.forEach(function (originalOffset) {
  89694. if (!normalData) {
  89695. return;
  89696. }
  89697. newPositionData.push(vertex.position.x);
  89698. newPositionData.push(vertex.position.y);
  89699. newPositionData.push(vertex.position.z);
  89700. newNormalData.push(normalData[originalOffset * 3]);
  89701. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89702. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89703. if (uvs && uvs.length) {
  89704. newUVsData.push(uvs[(originalOffset * 2)]);
  89705. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89706. }
  89707. else if (colorsData && colorsData.length) {
  89708. newColorsData.push(colorsData[(originalOffset * 4)]);
  89709. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89710. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89711. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89712. }
  89713. ++vertexCount;
  89714. });
  89715. }
  89716. }
  89717. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89718. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89719. var submeshesArray = this._reconstructedMesh.subMeshes;
  89720. this._reconstructedMesh.subMeshes = [];
  89721. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89722. var originalIndices = this._mesh.getIndices();
  89723. for (i = 0; i < newTriangles.length; ++i) {
  89724. t = newTriangles[i]; //now get the new referencing point for each vertex
  89725. [0, 1, 2].forEach(function (idx) {
  89726. var id = originalIndices[t.originalOffset + idx];
  89727. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89728. if (offset < 0)
  89729. offset = 0;
  89730. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89731. });
  89732. }
  89733. //overwriting the old vertex buffers and indices.
  89734. this._reconstructedMesh.setIndices(newIndicesArray);
  89735. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89736. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89737. if (newUVsData.length > 0)
  89738. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89739. if (newColorsData.length > 0)
  89740. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89741. //create submesh
  89742. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89743. if (submeshIndex > 0) {
  89744. this._reconstructedMesh.subMeshes = [];
  89745. submeshesArray.forEach(function (submesh) {
  89746. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89747. });
  89748. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89749. }
  89750. };
  89751. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89752. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89753. this._reconstructedMesh.material = this._mesh.material;
  89754. this._reconstructedMesh.parent = this._mesh.parent;
  89755. this._reconstructedMesh.isVisible = false;
  89756. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89757. };
  89758. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89759. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89760. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89761. if (t.deleted)
  89762. continue;
  89763. var s = this.references[vertex1.triangleStart + i].vertexId;
  89764. var v1 = t.vertices[(s + 1) % 3];
  89765. var v2 = t.vertices[(s + 2) % 3];
  89766. if ((v1 === vertex2 || v2 === vertex2)) {
  89767. deletedArray[i] = true;
  89768. delTr.push(t);
  89769. continue;
  89770. }
  89771. var d1 = v1.position.subtract(point);
  89772. d1 = d1.normalize();
  89773. var d2 = v2.position.subtract(point);
  89774. d2 = d2.normalize();
  89775. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89776. return true;
  89777. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89778. deletedArray[i] = false;
  89779. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89780. return true;
  89781. }
  89782. return false;
  89783. };
  89784. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89785. var newDeleted = deletedTriangles;
  89786. for (var i = 0; i < vertex.triangleCount; ++i) {
  89787. var ref = this.references[vertex.triangleStart + i];
  89788. var t = this.triangles[ref.triangleId];
  89789. if (t.deleted)
  89790. continue;
  89791. if (deletedArray[i] && t.deletePending) {
  89792. t.deleted = true;
  89793. newDeleted++;
  89794. continue;
  89795. }
  89796. t.vertices[ref.vertexId] = origVertex;
  89797. t.isDirty = true;
  89798. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89799. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89800. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89801. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89802. this.references.push(ref);
  89803. }
  89804. return newDeleted;
  89805. };
  89806. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89807. for (var i = 0; i < this.vertices.length; ++i) {
  89808. var vCount = [];
  89809. var vId = [];
  89810. var v = this.vertices[i];
  89811. var j;
  89812. for (j = 0; j < v.triangleCount; ++j) {
  89813. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89814. for (var ii = 0; ii < 3; ii++) {
  89815. var ofs = 0;
  89816. var vv = triangle.vertices[ii];
  89817. while (ofs < vCount.length) {
  89818. if (vId[ofs] === vv.id)
  89819. break;
  89820. ++ofs;
  89821. }
  89822. if (ofs === vCount.length) {
  89823. vCount.push(1);
  89824. vId.push(vv.id);
  89825. }
  89826. else {
  89827. vCount[ofs]++;
  89828. }
  89829. }
  89830. }
  89831. for (j = 0; j < vCount.length; ++j) {
  89832. if (vCount[j] === 1) {
  89833. this.vertices[vId[j]].isBorder = true;
  89834. }
  89835. else {
  89836. this.vertices[vId[j]].isBorder = false;
  89837. }
  89838. }
  89839. }
  89840. };
  89841. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89842. if (identifyBorders === void 0) { identifyBorders = false; }
  89843. var i;
  89844. if (!identifyBorders) {
  89845. var newTrianglesVector = [];
  89846. for (i = 0; i < this.triangles.length; ++i) {
  89847. if (!this.triangles[i].deleted) {
  89848. newTrianglesVector.push(this.triangles[i]);
  89849. }
  89850. }
  89851. this.triangles = newTrianglesVector;
  89852. }
  89853. for (i = 0; i < this.vertices.length; ++i) {
  89854. this.vertices[i].triangleCount = 0;
  89855. this.vertices[i].triangleStart = 0;
  89856. }
  89857. var t;
  89858. var j;
  89859. var v;
  89860. for (i = 0; i < this.triangles.length; ++i) {
  89861. t = this.triangles[i];
  89862. for (j = 0; j < 3; ++j) {
  89863. v = t.vertices[j];
  89864. v.triangleCount++;
  89865. }
  89866. }
  89867. var tStart = 0;
  89868. for (i = 0; i < this.vertices.length; ++i) {
  89869. this.vertices[i].triangleStart = tStart;
  89870. tStart += this.vertices[i].triangleCount;
  89871. this.vertices[i].triangleCount = 0;
  89872. }
  89873. var newReferences = new Array(this.triangles.length * 3);
  89874. for (i = 0; i < this.triangles.length; ++i) {
  89875. t = this.triangles[i];
  89876. for (j = 0; j < 3; ++j) {
  89877. v = t.vertices[j];
  89878. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89879. v.triangleCount++;
  89880. }
  89881. }
  89882. this.references = newReferences;
  89883. if (identifyBorders) {
  89884. this.identifyBorder();
  89885. }
  89886. };
  89887. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89888. var x = point.x;
  89889. var y = point.y;
  89890. var z = point.z;
  89891. 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
  89892. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89893. };
  89894. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89895. var q = vertex1.q.add(vertex2.q);
  89896. var border = vertex1.isBorder && vertex2.isBorder;
  89897. var error = 0;
  89898. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89899. if (qDet !== 0 && !border) {
  89900. if (!pointResult) {
  89901. pointResult = BABYLON.Vector3.Zero();
  89902. }
  89903. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89904. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89905. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89906. error = this.vertexError(q, pointResult);
  89907. }
  89908. else {
  89909. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89910. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89911. var error1 = this.vertexError(q, vertex1.position);
  89912. var error2 = this.vertexError(q, vertex2.position);
  89913. var error3 = this.vertexError(q, p3);
  89914. error = Math.min(error1, error2, error3);
  89915. if (error === error1) {
  89916. if (pointResult) {
  89917. pointResult.copyFrom(vertex1.position);
  89918. }
  89919. }
  89920. else if (error === error2) {
  89921. if (pointResult) {
  89922. pointResult.copyFrom(vertex2.position);
  89923. }
  89924. }
  89925. else {
  89926. if (pointResult) {
  89927. pointResult.copyFrom(p3);
  89928. }
  89929. }
  89930. }
  89931. return error;
  89932. };
  89933. return QuadraticErrorSimplification;
  89934. }());
  89935. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89936. })(BABYLON || (BABYLON = {}));
  89937. //# sourceMappingURL=babylon.meshSimplification.js.map
  89938. var BABYLON;
  89939. (function (BABYLON) {
  89940. var MeshLODLevel = /** @class */ (function () {
  89941. function MeshLODLevel(distance, mesh) {
  89942. this.distance = distance;
  89943. this.mesh = mesh;
  89944. }
  89945. return MeshLODLevel;
  89946. }());
  89947. BABYLON.MeshLODLevel = MeshLODLevel;
  89948. })(BABYLON || (BABYLON = {}));
  89949. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89950. var BABYLON;
  89951. (function (BABYLON) {
  89952. /**
  89953. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89954. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89955. */
  89956. var SceneOptimization = /** @class */ (function () {
  89957. /**
  89958. * Creates the SceneOptimization object
  89959. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89960. * @param desc defines the description associated with the optimization
  89961. */
  89962. function SceneOptimization(
  89963. /**
  89964. * Defines the priority of this optimization (0 by default which means first in the list)
  89965. */
  89966. priority) {
  89967. if (priority === void 0) { priority = 0; }
  89968. this.priority = priority;
  89969. }
  89970. /**
  89971. * Gets a string describing the action executed by the current optimization
  89972. * @returns description string
  89973. */
  89974. SceneOptimization.prototype.getDescription = function () {
  89975. return "";
  89976. };
  89977. /**
  89978. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89979. * @param scene defines the current scene where to apply this optimization
  89980. * @param optimizer defines the current optimizer
  89981. * @returns true if everything that can be done was applied
  89982. */
  89983. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89984. return true;
  89985. };
  89986. ;
  89987. return SceneOptimization;
  89988. }());
  89989. BABYLON.SceneOptimization = SceneOptimization;
  89990. /**
  89991. * Defines an optimization used to reduce the size of render target textures
  89992. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89993. */
  89994. var TextureOptimization = /** @class */ (function (_super) {
  89995. __extends(TextureOptimization, _super);
  89996. /**
  89997. * Creates the TextureOptimization object
  89998. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89999. * @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
  90000. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90001. */
  90002. function TextureOptimization(
  90003. /**
  90004. * Defines the priority of this optimization (0 by default which means first in the list)
  90005. */
  90006. priority,
  90007. /**
  90008. * 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
  90009. */
  90010. maximumSize,
  90011. /**
  90012. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90013. */
  90014. step) {
  90015. if (priority === void 0) { priority = 0; }
  90016. if (maximumSize === void 0) { maximumSize = 1024; }
  90017. if (step === void 0) { step = 0.5; }
  90018. var _this = _super.call(this, priority) || this;
  90019. _this.priority = priority;
  90020. _this.maximumSize = maximumSize;
  90021. _this.step = step;
  90022. return _this;
  90023. }
  90024. /**
  90025. * Gets a string describing the action executed by the current optimization
  90026. * @returns description string
  90027. */
  90028. TextureOptimization.prototype.getDescription = function () {
  90029. return "Reducing render target texture size to " + this.maximumSize;
  90030. };
  90031. /**
  90032. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90033. * @param scene defines the current scene where to apply this optimization
  90034. * @param optimizer defines the current optimizer
  90035. * @returns true if everything that can be done was applied
  90036. */
  90037. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90038. var allDone = true;
  90039. for (var index = 0; index < scene.textures.length; index++) {
  90040. var texture = scene.textures[index];
  90041. if (!texture.canRescale || texture.getContext) {
  90042. continue;
  90043. }
  90044. var currentSize = texture.getSize();
  90045. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90046. if (maxDimension > this.maximumSize) {
  90047. texture.scale(this.step);
  90048. allDone = false;
  90049. }
  90050. }
  90051. return allDone;
  90052. };
  90053. return TextureOptimization;
  90054. }(SceneOptimization));
  90055. BABYLON.TextureOptimization = TextureOptimization;
  90056. /**
  90057. * Defines an optimization used to increase or decrease the rendering resolution
  90058. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90059. */
  90060. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90061. __extends(HardwareScalingOptimization, _super);
  90062. /**
  90063. * Creates the HardwareScalingOptimization object
  90064. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90065. * @param maximumScale defines the maximum scale to use (2 by default)
  90066. * @param step defines the step to use between two passes (0.5 by default)
  90067. */
  90068. function HardwareScalingOptimization(
  90069. /**
  90070. * Defines the priority of this optimization (0 by default which means first in the list)
  90071. */
  90072. priority,
  90073. /**
  90074. * Defines the maximum scale to use (2 by default)
  90075. */
  90076. maximumScale,
  90077. /**
  90078. * Defines the step to use between two passes (0.5 by default)
  90079. */
  90080. step) {
  90081. if (priority === void 0) { priority = 0; }
  90082. if (maximumScale === void 0) { maximumScale = 2; }
  90083. if (step === void 0) { step = 0.25; }
  90084. var _this = _super.call(this, priority) || this;
  90085. _this.priority = priority;
  90086. _this.maximumScale = maximumScale;
  90087. _this.step = step;
  90088. _this._currentScale = -1;
  90089. _this._directionOffset = 1;
  90090. return _this;
  90091. }
  90092. /**
  90093. * Gets a string describing the action executed by the current optimization
  90094. * @return description string
  90095. */
  90096. HardwareScalingOptimization.prototype.getDescription = function () {
  90097. return "Setting hardware scaling level to " + this._currentScale;
  90098. };
  90099. /**
  90100. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90101. * @param scene defines the current scene where to apply this optimization
  90102. * @param optimizer defines the current optimizer
  90103. * @returns true if everything that can be done was applied
  90104. */
  90105. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90106. if (this._currentScale === -1) {
  90107. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90108. if (this._currentScale > this.maximumScale) {
  90109. this._directionOffset = -1;
  90110. }
  90111. }
  90112. this._currentScale += this._directionOffset * this.step;
  90113. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90114. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90115. };
  90116. ;
  90117. return HardwareScalingOptimization;
  90118. }(SceneOptimization));
  90119. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90120. /**
  90121. * Defines an optimization used to remove shadows
  90122. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90123. */
  90124. var ShadowsOptimization = /** @class */ (function (_super) {
  90125. __extends(ShadowsOptimization, _super);
  90126. function ShadowsOptimization() {
  90127. return _super !== null && _super.apply(this, arguments) || this;
  90128. }
  90129. /**
  90130. * Gets a string describing the action executed by the current optimization
  90131. * @return description string
  90132. */
  90133. ShadowsOptimization.prototype.getDescription = function () {
  90134. return "Turning shadows on/off";
  90135. };
  90136. /**
  90137. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90138. * @param scene defines the current scene where to apply this optimization
  90139. * @param optimizer defines the current optimizer
  90140. * @returns true if everything that can be done was applied
  90141. */
  90142. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90143. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90144. return true;
  90145. };
  90146. ;
  90147. return ShadowsOptimization;
  90148. }(SceneOptimization));
  90149. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90150. /**
  90151. * Defines an optimization used to turn post-processes off
  90152. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90153. */
  90154. var PostProcessesOptimization = /** @class */ (function (_super) {
  90155. __extends(PostProcessesOptimization, _super);
  90156. function PostProcessesOptimization() {
  90157. return _super !== null && _super.apply(this, arguments) || this;
  90158. }
  90159. /**
  90160. * Gets a string describing the action executed by the current optimization
  90161. * @return description string
  90162. */
  90163. PostProcessesOptimization.prototype.getDescription = function () {
  90164. return "Turning post-processes on/off";
  90165. };
  90166. /**
  90167. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90168. * @param scene defines the current scene where to apply this optimization
  90169. * @param optimizer defines the current optimizer
  90170. * @returns true if everything that can be done was applied
  90171. */
  90172. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90173. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90174. return true;
  90175. };
  90176. ;
  90177. return PostProcessesOptimization;
  90178. }(SceneOptimization));
  90179. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90180. /**
  90181. * Defines an optimization used to turn lens flares off
  90182. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90183. */
  90184. var LensFlaresOptimization = /** @class */ (function (_super) {
  90185. __extends(LensFlaresOptimization, _super);
  90186. function LensFlaresOptimization() {
  90187. return _super !== null && _super.apply(this, arguments) || this;
  90188. }
  90189. /**
  90190. * Gets a string describing the action executed by the current optimization
  90191. * @return description string
  90192. */
  90193. LensFlaresOptimization.prototype.getDescription = function () {
  90194. return "Turning lens flares on/off";
  90195. };
  90196. /**
  90197. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90198. * @param scene defines the current scene where to apply this optimization
  90199. * @param optimizer defines the current optimizer
  90200. * @returns true if everything that can be done was applied
  90201. */
  90202. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90203. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90204. return true;
  90205. };
  90206. ;
  90207. return LensFlaresOptimization;
  90208. }(SceneOptimization));
  90209. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90210. /**
  90211. * Defines an optimization based on user defined callback.
  90212. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90213. */
  90214. var CustomOptimization = /** @class */ (function (_super) {
  90215. __extends(CustomOptimization, _super);
  90216. function CustomOptimization() {
  90217. return _super !== null && _super.apply(this, arguments) || this;
  90218. }
  90219. /**
  90220. * Gets a string describing the action executed by the current optimization
  90221. * @returns description string
  90222. */
  90223. CustomOptimization.prototype.getDescription = function () {
  90224. if (this.onGetDescription) {
  90225. return this.onGetDescription();
  90226. }
  90227. return "Running user defined callback";
  90228. };
  90229. /**
  90230. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90231. * @param scene defines the current scene where to apply this optimization
  90232. * @param optimizer defines the current optimizer
  90233. * @returns true if everything that can be done was applied
  90234. */
  90235. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90236. if (this.onApply) {
  90237. return this.onApply(scene, optimizer);
  90238. }
  90239. return true;
  90240. };
  90241. ;
  90242. return CustomOptimization;
  90243. }(SceneOptimization));
  90244. BABYLON.CustomOptimization = CustomOptimization;
  90245. /**
  90246. * Defines an optimization used to turn particles off
  90247. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90248. */
  90249. var ParticlesOptimization = /** @class */ (function (_super) {
  90250. __extends(ParticlesOptimization, _super);
  90251. function ParticlesOptimization() {
  90252. return _super !== null && _super.apply(this, arguments) || this;
  90253. }
  90254. /**
  90255. * Gets a string describing the action executed by the current optimization
  90256. * @return description string
  90257. */
  90258. ParticlesOptimization.prototype.getDescription = function () {
  90259. return "Turning particles on/off";
  90260. };
  90261. /**
  90262. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90263. * @param scene defines the current scene where to apply this optimization
  90264. * @param optimizer defines the current optimizer
  90265. * @returns true if everything that can be done was applied
  90266. */
  90267. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90268. scene.particlesEnabled = optimizer.isInImprovementMode;
  90269. return true;
  90270. };
  90271. ;
  90272. return ParticlesOptimization;
  90273. }(SceneOptimization));
  90274. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90275. /**
  90276. * Defines an optimization used to turn render targets off
  90277. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90278. */
  90279. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90280. __extends(RenderTargetsOptimization, _super);
  90281. function RenderTargetsOptimization() {
  90282. return _super !== null && _super.apply(this, arguments) || this;
  90283. }
  90284. /**
  90285. * Gets a string describing the action executed by the current optimization
  90286. * @return description string
  90287. */
  90288. RenderTargetsOptimization.prototype.getDescription = function () {
  90289. return "Turning render targets off";
  90290. };
  90291. /**
  90292. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90293. * @param scene defines the current scene where to apply this optimization
  90294. * @param optimizer defines the current optimizer
  90295. * @returns true if everything that can be done was applied
  90296. */
  90297. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90298. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90299. return true;
  90300. };
  90301. ;
  90302. return RenderTargetsOptimization;
  90303. }(SceneOptimization));
  90304. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90305. /**
  90306. * Defines an optimization used to merge meshes with compatible materials
  90307. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90308. */
  90309. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90310. __extends(MergeMeshesOptimization, _super);
  90311. function MergeMeshesOptimization() {
  90312. var _this = _super !== null && _super.apply(this, arguments) || this;
  90313. _this._canBeMerged = function (abstractMesh) {
  90314. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90315. return false;
  90316. }
  90317. var mesh = abstractMesh;
  90318. if (!mesh.isVisible || !mesh.isEnabled()) {
  90319. return false;
  90320. }
  90321. if (mesh.instances.length > 0) {
  90322. return false;
  90323. }
  90324. if (mesh.skeleton || mesh.hasLODLevels) {
  90325. return false;
  90326. }
  90327. if (mesh.parent) {
  90328. return false;
  90329. }
  90330. return true;
  90331. };
  90332. return _this;
  90333. }
  90334. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90335. /**
  90336. * Gets or sets a boolean which defines if optimization octree has to be updated
  90337. */
  90338. get: function () {
  90339. return MergeMeshesOptimization._UpdateSelectionTree;
  90340. },
  90341. /**
  90342. * Gets or sets a boolean which defines if optimization octree has to be updated
  90343. */
  90344. set: function (value) {
  90345. MergeMeshesOptimization._UpdateSelectionTree = value;
  90346. },
  90347. enumerable: true,
  90348. configurable: true
  90349. });
  90350. /**
  90351. * Gets a string describing the action executed by the current optimization
  90352. * @return description string
  90353. */
  90354. MergeMeshesOptimization.prototype.getDescription = function () {
  90355. return "Merging similar meshes together";
  90356. };
  90357. /**
  90358. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90359. * @param scene defines the current scene where to apply this optimization
  90360. * @param optimizer defines the current optimizer
  90361. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90362. * @returns true if everything that can be done was applied
  90363. */
  90364. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90365. var globalPool = scene.meshes.slice(0);
  90366. var globalLength = globalPool.length;
  90367. for (var index = 0; index < globalLength; index++) {
  90368. var currentPool = new Array();
  90369. var current = globalPool[index];
  90370. // Checks
  90371. if (!this._canBeMerged(current)) {
  90372. continue;
  90373. }
  90374. currentPool.push(current);
  90375. // Find compatible meshes
  90376. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90377. var otherMesh = globalPool[subIndex];
  90378. if (!this._canBeMerged(otherMesh)) {
  90379. continue;
  90380. }
  90381. if (otherMesh.material !== current.material) {
  90382. continue;
  90383. }
  90384. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90385. continue;
  90386. }
  90387. currentPool.push(otherMesh);
  90388. globalLength--;
  90389. globalPool.splice(subIndex, 1);
  90390. subIndex--;
  90391. }
  90392. if (currentPool.length < 2) {
  90393. continue;
  90394. }
  90395. // Merge meshes
  90396. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90397. }
  90398. if (updateSelectionTree != undefined) {
  90399. if (updateSelectionTree) {
  90400. scene.createOrUpdateSelectionOctree();
  90401. }
  90402. }
  90403. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90404. scene.createOrUpdateSelectionOctree();
  90405. }
  90406. return true;
  90407. };
  90408. ;
  90409. MergeMeshesOptimization._UpdateSelectionTree = false;
  90410. return MergeMeshesOptimization;
  90411. }(SceneOptimization));
  90412. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90413. /**
  90414. * Defines a list of options used by SceneOptimizer
  90415. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90416. */
  90417. var SceneOptimizerOptions = /** @class */ (function () {
  90418. /**
  90419. * Creates a new list of options used by SceneOptimizer
  90420. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90421. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90422. */
  90423. function SceneOptimizerOptions(
  90424. /**
  90425. * Defines the target frame rate to reach (60 by default)
  90426. */
  90427. targetFrameRate,
  90428. /**
  90429. * Defines the interval between two checkes (2000ms by default)
  90430. */
  90431. trackerDuration) {
  90432. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90433. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90434. this.targetFrameRate = targetFrameRate;
  90435. this.trackerDuration = trackerDuration;
  90436. /**
  90437. * Gets the list of optimizations to apply
  90438. */
  90439. this.optimizations = new Array();
  90440. }
  90441. /**
  90442. * Add a new optimization
  90443. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90444. * @returns the current SceneOptimizerOptions
  90445. */
  90446. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90447. this.optimizations.push(optimization);
  90448. return this;
  90449. };
  90450. /**
  90451. * Add a new custom optimization
  90452. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90453. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90454. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90455. * @returns the current SceneOptimizerOptions
  90456. */
  90457. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90458. if (priority === void 0) { priority = 0; }
  90459. var optimization = new CustomOptimization(priority);
  90460. optimization.onApply = onApply;
  90461. optimization.onGetDescription = onGetDescription;
  90462. this.optimizations.push(optimization);
  90463. return this;
  90464. };
  90465. /**
  90466. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90467. * @param targetFrameRate defines the target frame rate (60 by default)
  90468. * @returns a SceneOptimizerOptions object
  90469. */
  90470. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90471. var result = new SceneOptimizerOptions(targetFrameRate);
  90472. var priority = 0;
  90473. result.addOptimization(new MergeMeshesOptimization(priority));
  90474. result.addOptimization(new ShadowsOptimization(priority));
  90475. result.addOptimization(new LensFlaresOptimization(priority));
  90476. // Next priority
  90477. priority++;
  90478. result.addOptimization(new PostProcessesOptimization(priority));
  90479. result.addOptimization(new ParticlesOptimization(priority));
  90480. // Next priority
  90481. priority++;
  90482. result.addOptimization(new TextureOptimization(priority, 1024));
  90483. return result;
  90484. };
  90485. /**
  90486. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90487. * @param targetFrameRate defines the target frame rate (60 by default)
  90488. * @returns a SceneOptimizerOptions object
  90489. */
  90490. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90491. var result = new SceneOptimizerOptions(targetFrameRate);
  90492. var priority = 0;
  90493. result.addOptimization(new MergeMeshesOptimization(priority));
  90494. result.addOptimization(new ShadowsOptimization(priority));
  90495. result.addOptimization(new LensFlaresOptimization(priority));
  90496. // Next priority
  90497. priority++;
  90498. result.addOptimization(new PostProcessesOptimization(priority));
  90499. result.addOptimization(new ParticlesOptimization(priority));
  90500. // Next priority
  90501. priority++;
  90502. result.addOptimization(new TextureOptimization(priority, 512));
  90503. // Next priority
  90504. priority++;
  90505. result.addOptimization(new RenderTargetsOptimization(priority));
  90506. // Next priority
  90507. priority++;
  90508. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90509. return result;
  90510. };
  90511. /**
  90512. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90513. * @param targetFrameRate defines the target frame rate (60 by default)
  90514. * @returns a SceneOptimizerOptions object
  90515. */
  90516. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90517. var result = new SceneOptimizerOptions(targetFrameRate);
  90518. var priority = 0;
  90519. result.addOptimization(new MergeMeshesOptimization(priority));
  90520. result.addOptimization(new ShadowsOptimization(priority));
  90521. result.addOptimization(new LensFlaresOptimization(priority));
  90522. // Next priority
  90523. priority++;
  90524. result.addOptimization(new PostProcessesOptimization(priority));
  90525. result.addOptimization(new ParticlesOptimization(priority));
  90526. // Next priority
  90527. priority++;
  90528. result.addOptimization(new TextureOptimization(priority, 256));
  90529. // Next priority
  90530. priority++;
  90531. result.addOptimization(new RenderTargetsOptimization(priority));
  90532. // Next priority
  90533. priority++;
  90534. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90535. return result;
  90536. };
  90537. return SceneOptimizerOptions;
  90538. }());
  90539. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90540. /**
  90541. * Class used to run optimizations in order to reach a target frame rate
  90542. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90543. */
  90544. var SceneOptimizer = /** @class */ (function () {
  90545. /**
  90546. * Creates a new SceneOptimizer
  90547. * @param scene defines the scene to work on
  90548. * @param options defines the options to use with the SceneOptimizer
  90549. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90550. * @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)
  90551. */
  90552. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90553. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90554. if (improvementMode === void 0) { improvementMode = false; }
  90555. var _this = this;
  90556. this._isRunning = false;
  90557. this._currentPriorityLevel = 0;
  90558. this._targetFrameRate = 60;
  90559. this._trackerDuration = 2000;
  90560. this._currentFrameRate = 0;
  90561. this._improvementMode = false;
  90562. /**
  90563. * Defines an observable called when the optimizer reaches the target frame rate
  90564. */
  90565. this.onSuccessObservable = new BABYLON.Observable();
  90566. /**
  90567. * Defines an observable called when the optimizer enables an optimization
  90568. */
  90569. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90570. /**
  90571. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90572. */
  90573. this.onFailureObservable = new BABYLON.Observable();
  90574. if (!options) {
  90575. this._options = new SceneOptimizerOptions();
  90576. }
  90577. else {
  90578. this._options = options;
  90579. }
  90580. if (this._options.targetFrameRate) {
  90581. this._targetFrameRate = this._options.targetFrameRate;
  90582. }
  90583. if (this._options.trackerDuration) {
  90584. this._trackerDuration = this._options.trackerDuration;
  90585. }
  90586. if (autoGeneratePriorities) {
  90587. var priority = 0;
  90588. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90589. var optim = _a[_i];
  90590. optim.priority = priority++;
  90591. }
  90592. }
  90593. this._improvementMode = improvementMode;
  90594. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90595. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90596. _this._sceneDisposeObserver = null;
  90597. _this.dispose();
  90598. });
  90599. }
  90600. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90601. /**
  90602. * Gets a boolean indicating if the optimizer is in improvement mode
  90603. */
  90604. get: function () {
  90605. return this._improvementMode;
  90606. },
  90607. enumerable: true,
  90608. configurable: true
  90609. });
  90610. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90611. /**
  90612. * Gets the current priority level (0 at start)
  90613. */
  90614. get: function () {
  90615. return this._currentPriorityLevel;
  90616. },
  90617. enumerable: true,
  90618. configurable: true
  90619. });
  90620. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90621. /**
  90622. * Gets the current frame rate checked by the SceneOptimizer
  90623. */
  90624. get: function () {
  90625. return this._currentFrameRate;
  90626. },
  90627. enumerable: true,
  90628. configurable: true
  90629. });
  90630. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90631. /**
  90632. * Gets or sets the current target frame rate (60 by default)
  90633. */
  90634. get: function () {
  90635. return this._targetFrameRate;
  90636. },
  90637. /**
  90638. * Gets or sets the current target frame rate (60 by default)
  90639. */
  90640. set: function (value) {
  90641. this._targetFrameRate = value;
  90642. },
  90643. enumerable: true,
  90644. configurable: true
  90645. });
  90646. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90647. /**
  90648. * Gets or sets the current interval between two checks (every 2000ms by default)
  90649. */
  90650. get: function () {
  90651. return this._trackerDuration;
  90652. },
  90653. /**
  90654. * Gets or sets the current interval between two checks (every 2000ms by default)
  90655. */
  90656. set: function (value) {
  90657. this._trackerDuration = value;
  90658. },
  90659. enumerable: true,
  90660. configurable: true
  90661. });
  90662. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90663. /**
  90664. * Gets the list of active optimizations
  90665. */
  90666. get: function () {
  90667. return this._options.optimizations;
  90668. },
  90669. enumerable: true,
  90670. configurable: true
  90671. });
  90672. /**
  90673. * Stops the current optimizer
  90674. */
  90675. SceneOptimizer.prototype.stop = function () {
  90676. this._isRunning = false;
  90677. };
  90678. /**
  90679. * Reset the optimizer to initial step (current priority level = 0)
  90680. */
  90681. SceneOptimizer.prototype.reset = function () {
  90682. this._currentPriorityLevel = 0;
  90683. };
  90684. /**
  90685. * Start the optimizer. By default it will try to reach a specific framerate
  90686. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90687. */
  90688. SceneOptimizer.prototype.start = function () {
  90689. var _this = this;
  90690. if (this._isRunning) {
  90691. return;
  90692. }
  90693. this._isRunning = true;
  90694. // Let's wait for the scene to be ready before running our check
  90695. this._scene.executeWhenReady(function () {
  90696. setTimeout(function () {
  90697. _this._checkCurrentState();
  90698. }, _this._trackerDuration);
  90699. });
  90700. };
  90701. SceneOptimizer.prototype._checkCurrentState = function () {
  90702. var _this = this;
  90703. if (!this._isRunning) {
  90704. return;
  90705. }
  90706. var scene = this._scene;
  90707. var options = this._options;
  90708. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90709. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90710. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90711. this._isRunning = false;
  90712. this.onSuccessObservable.notifyObservers(this);
  90713. return;
  90714. }
  90715. // Apply current level of optimizations
  90716. var allDone = true;
  90717. var noOptimizationApplied = true;
  90718. for (var index = 0; index < options.optimizations.length; index++) {
  90719. var optimization = options.optimizations[index];
  90720. if (optimization.priority === this._currentPriorityLevel) {
  90721. noOptimizationApplied = false;
  90722. allDone = allDone && optimization.apply(scene, this);
  90723. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90724. }
  90725. }
  90726. // If no optimization was applied, this is a failure :(
  90727. if (noOptimizationApplied) {
  90728. this._isRunning = false;
  90729. this.onFailureObservable.notifyObservers(this);
  90730. return;
  90731. }
  90732. // If all optimizations were done, move to next level
  90733. if (allDone) {
  90734. this._currentPriorityLevel++;
  90735. }
  90736. // Let's the system running for a specific amount of time before checking FPS
  90737. scene.executeWhenReady(function () {
  90738. setTimeout(function () {
  90739. _this._checkCurrentState();
  90740. }, _this._trackerDuration);
  90741. });
  90742. };
  90743. /**
  90744. * Release all resources
  90745. */
  90746. SceneOptimizer.prototype.dispose = function () {
  90747. this.stop();
  90748. this.onSuccessObservable.clear();
  90749. this.onFailureObservable.clear();
  90750. this.onNewOptimizationAppliedObservable.clear();
  90751. if (this._sceneDisposeObserver) {
  90752. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90753. }
  90754. };
  90755. /**
  90756. * Helper function to create a SceneOptimizer with one single line of code
  90757. * @param scene defines the scene to work on
  90758. * @param options defines the options to use with the SceneOptimizer
  90759. * @param onSuccess defines a callback to call on success
  90760. * @param onFailure defines a callback to call on failure
  90761. * @returns the new SceneOptimizer object
  90762. */
  90763. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90764. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90765. if (onSuccess) {
  90766. optimizer.onSuccessObservable.add(function () {
  90767. onSuccess();
  90768. });
  90769. }
  90770. if (onFailure) {
  90771. optimizer.onFailureObservable.add(function () {
  90772. onFailure();
  90773. });
  90774. }
  90775. optimizer.start();
  90776. return optimizer;
  90777. };
  90778. return SceneOptimizer;
  90779. }());
  90780. BABYLON.SceneOptimizer = SceneOptimizer;
  90781. })(BABYLON || (BABYLON = {}));
  90782. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90783. var BABYLON;
  90784. (function (BABYLON) {
  90785. var OutlineRenderer = /** @class */ (function () {
  90786. function OutlineRenderer(scene) {
  90787. this.zOffset = 1;
  90788. this._scene = scene;
  90789. }
  90790. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90791. var _this = this;
  90792. if (useOverlay === void 0) { useOverlay = false; }
  90793. var scene = this._scene;
  90794. var engine = this._scene.getEngine();
  90795. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90796. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90797. return;
  90798. }
  90799. var mesh = subMesh.getRenderingMesh();
  90800. var material = subMesh.getMaterial();
  90801. if (!material || !scene.activeCamera) {
  90802. return;
  90803. }
  90804. engine.enableEffect(this._effect);
  90805. // Logarithmic depth
  90806. if (material.useLogarithmicDepth) {
  90807. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90808. }
  90809. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90810. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90811. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90812. // Bones
  90813. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90814. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90815. }
  90816. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90817. // Alpha test
  90818. if (material && material.needAlphaTesting()) {
  90819. var alphaTexture = material.getAlphaTestTexture();
  90820. if (alphaTexture) {
  90821. this._effect.setTexture("diffuseSampler", alphaTexture);
  90822. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90823. }
  90824. }
  90825. engine.setZOffset(-this.zOffset);
  90826. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90827. engine.setZOffset(0);
  90828. };
  90829. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90830. var defines = [];
  90831. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90832. var mesh = subMesh.getMesh();
  90833. var material = subMesh.getMaterial();
  90834. if (material) {
  90835. // Alpha test
  90836. if (material.needAlphaTesting()) {
  90837. defines.push("#define ALPHATEST");
  90838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90839. attribs.push(BABYLON.VertexBuffer.UVKind);
  90840. defines.push("#define UV1");
  90841. }
  90842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90843. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90844. defines.push("#define UV2");
  90845. }
  90846. }
  90847. //Logarithmic depth
  90848. if (material.useLogarithmicDepth) {
  90849. defines.push("#define LOGARITHMICDEPTH");
  90850. }
  90851. }
  90852. // Bones
  90853. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90856. if (mesh.numBoneInfluencers > 4) {
  90857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90859. }
  90860. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90861. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90862. }
  90863. else {
  90864. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90865. }
  90866. // Instances
  90867. if (useInstances) {
  90868. defines.push("#define INSTANCES");
  90869. attribs.push("world0");
  90870. attribs.push("world1");
  90871. attribs.push("world2");
  90872. attribs.push("world3");
  90873. }
  90874. // Get correct effect
  90875. var join = defines.join("\n");
  90876. if (this._cachedDefines !== join) {
  90877. this._cachedDefines = join;
  90878. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90879. }
  90880. return this._effect.isReady();
  90881. };
  90882. return OutlineRenderer;
  90883. }());
  90884. BABYLON.OutlineRenderer = OutlineRenderer;
  90885. })(BABYLON || (BABYLON = {}));
  90886. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90887. var BABYLON;
  90888. (function (BABYLON) {
  90889. var FaceAdjacencies = /** @class */ (function () {
  90890. function FaceAdjacencies() {
  90891. this.edges = new Array();
  90892. this.edgesConnectedCount = 0;
  90893. }
  90894. return FaceAdjacencies;
  90895. }());
  90896. var EdgesRenderer = /** @class */ (function () {
  90897. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90898. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90899. if (epsilon === void 0) { epsilon = 0.95; }
  90900. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90901. this.edgesWidthScalerForOrthographic = 1000.0;
  90902. this.edgesWidthScalerForPerspective = 50.0;
  90903. this._linesPositions = new Array();
  90904. this._linesNormals = new Array();
  90905. this._linesIndices = new Array();
  90906. this._buffers = {};
  90907. this._checkVerticesInsteadOfIndices = false;
  90908. this._source = source;
  90909. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90910. this._epsilon = epsilon;
  90911. this._prepareRessources();
  90912. this._generateEdgesLines();
  90913. }
  90914. EdgesRenderer.prototype._prepareRessources = function () {
  90915. if (this._lineShader) {
  90916. return;
  90917. }
  90918. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90919. attributes: ["position", "normal"],
  90920. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90921. });
  90922. this._lineShader.disableDepthWrite = true;
  90923. this._lineShader.backFaceCulling = false;
  90924. };
  90925. EdgesRenderer.prototype._rebuild = function () {
  90926. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90927. if (buffer) {
  90928. buffer._rebuild();
  90929. }
  90930. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90931. if (buffer) {
  90932. buffer._rebuild();
  90933. }
  90934. var scene = this._source.getScene();
  90935. var engine = scene.getEngine();
  90936. this._ib = engine.createIndexBuffer(this._linesIndices);
  90937. };
  90938. EdgesRenderer.prototype.dispose = function () {
  90939. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90940. if (buffer) {
  90941. buffer.dispose();
  90942. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90943. }
  90944. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90945. if (buffer) {
  90946. buffer.dispose();
  90947. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90948. }
  90949. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90950. this._lineShader.dispose();
  90951. };
  90952. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90953. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90954. return 0;
  90955. }
  90956. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90957. return 1;
  90958. }
  90959. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90960. return 2;
  90961. }
  90962. return -1;
  90963. };
  90964. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90965. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90966. return 0;
  90967. }
  90968. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90969. return 1;
  90970. }
  90971. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90972. return 2;
  90973. }
  90974. return -1;
  90975. };
  90976. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90977. var needToCreateLine;
  90978. if (edge === undefined) {
  90979. needToCreateLine = true;
  90980. }
  90981. else {
  90982. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90983. needToCreateLine = dotProduct < this._epsilon;
  90984. }
  90985. if (needToCreateLine) {
  90986. var offset = this._linesPositions.length / 3;
  90987. var normal = p0.subtract(p1);
  90988. normal.normalize();
  90989. // Positions
  90990. this._linesPositions.push(p0.x);
  90991. this._linesPositions.push(p0.y);
  90992. this._linesPositions.push(p0.z);
  90993. this._linesPositions.push(p0.x);
  90994. this._linesPositions.push(p0.y);
  90995. this._linesPositions.push(p0.z);
  90996. this._linesPositions.push(p1.x);
  90997. this._linesPositions.push(p1.y);
  90998. this._linesPositions.push(p1.z);
  90999. this._linesPositions.push(p1.x);
  91000. this._linesPositions.push(p1.y);
  91001. this._linesPositions.push(p1.z);
  91002. // Normals
  91003. this._linesNormals.push(p1.x);
  91004. this._linesNormals.push(p1.y);
  91005. this._linesNormals.push(p1.z);
  91006. this._linesNormals.push(-1);
  91007. this._linesNormals.push(p1.x);
  91008. this._linesNormals.push(p1.y);
  91009. this._linesNormals.push(p1.z);
  91010. this._linesNormals.push(1);
  91011. this._linesNormals.push(p0.x);
  91012. this._linesNormals.push(p0.y);
  91013. this._linesNormals.push(p0.z);
  91014. this._linesNormals.push(-1);
  91015. this._linesNormals.push(p0.x);
  91016. this._linesNormals.push(p0.y);
  91017. this._linesNormals.push(p0.z);
  91018. this._linesNormals.push(1);
  91019. // Indices
  91020. this._linesIndices.push(offset);
  91021. this._linesIndices.push(offset + 1);
  91022. this._linesIndices.push(offset + 2);
  91023. this._linesIndices.push(offset);
  91024. this._linesIndices.push(offset + 2);
  91025. this._linesIndices.push(offset + 3);
  91026. }
  91027. };
  91028. EdgesRenderer.prototype._generateEdgesLines = function () {
  91029. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91030. var indices = this._source.getIndices();
  91031. if (!indices || !positions) {
  91032. return;
  91033. }
  91034. // First let's find adjacencies
  91035. var adjacencies = new Array();
  91036. var faceNormals = new Array();
  91037. var index;
  91038. var faceAdjacencies;
  91039. // Prepare faces
  91040. for (index = 0; index < indices.length; index += 3) {
  91041. faceAdjacencies = new FaceAdjacencies();
  91042. var p0Index = indices[index];
  91043. var p1Index = indices[index + 1];
  91044. var p2Index = indices[index + 2];
  91045. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91046. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91047. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91048. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91049. faceNormal.normalize();
  91050. faceNormals.push(faceNormal);
  91051. adjacencies.push(faceAdjacencies);
  91052. }
  91053. // Scan
  91054. for (index = 0; index < adjacencies.length; index++) {
  91055. faceAdjacencies = adjacencies[index];
  91056. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91057. var otherFaceAdjacencies = adjacencies[otherIndex];
  91058. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91059. break;
  91060. }
  91061. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91062. continue;
  91063. }
  91064. var otherP0 = indices[otherIndex * 3];
  91065. var otherP1 = indices[otherIndex * 3 + 1];
  91066. var otherP2 = indices[otherIndex * 3 + 2];
  91067. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91068. var otherEdgeIndex = 0;
  91069. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91070. continue;
  91071. }
  91072. switch (edgeIndex) {
  91073. case 0:
  91074. if (this._checkVerticesInsteadOfIndices) {
  91075. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91076. }
  91077. else {
  91078. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91079. }
  91080. break;
  91081. case 1:
  91082. if (this._checkVerticesInsteadOfIndices) {
  91083. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91084. }
  91085. else {
  91086. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91087. }
  91088. break;
  91089. case 2:
  91090. if (this._checkVerticesInsteadOfIndices) {
  91091. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91092. }
  91093. else {
  91094. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91095. }
  91096. break;
  91097. }
  91098. if (otherEdgeIndex === -1) {
  91099. continue;
  91100. }
  91101. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91102. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91103. faceAdjacencies.edgesConnectedCount++;
  91104. otherFaceAdjacencies.edgesConnectedCount++;
  91105. if (faceAdjacencies.edgesConnectedCount === 3) {
  91106. break;
  91107. }
  91108. }
  91109. }
  91110. }
  91111. // Create lines
  91112. for (index = 0; index < adjacencies.length; index++) {
  91113. // 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
  91114. var current = adjacencies[index];
  91115. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91116. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91117. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91118. }
  91119. // Merge into a single mesh
  91120. var engine = this._source.getScene().getEngine();
  91121. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91122. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91123. this._ib = engine.createIndexBuffer(this._linesIndices);
  91124. this._indicesCount = this._linesIndices.length;
  91125. };
  91126. EdgesRenderer.prototype.render = function () {
  91127. var scene = this._source.getScene();
  91128. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91129. return;
  91130. }
  91131. var engine = scene.getEngine();
  91132. this._lineShader._preBind();
  91133. // VBOs
  91134. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91135. scene.resetCachedMaterial();
  91136. this._lineShader.setColor4("color", this._source.edgesColor);
  91137. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91138. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91139. }
  91140. else {
  91141. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91142. }
  91143. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91144. this._lineShader.bind(this._source.getWorldMatrix());
  91145. // Draw order
  91146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91147. this._lineShader.unbind();
  91148. engine.setDepthWrite(true);
  91149. };
  91150. return EdgesRenderer;
  91151. }());
  91152. BABYLON.EdgesRenderer = EdgesRenderer;
  91153. })(BABYLON || (BABYLON = {}));
  91154. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91155. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91156. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91157. s = arguments[i];
  91158. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91159. t[p] = s[p];
  91160. }
  91161. return t;
  91162. };
  91163. var BABYLON;
  91164. (function (BABYLON) {
  91165. /**
  91166. * The effect layer Helps adding post process effect blended with the main pass.
  91167. *
  91168. * This can be for instance use to generate glow or higlight effects on the scene.
  91169. *
  91170. * The effect layer class can not be used directly and is intented to inherited from to be
  91171. * customized per effects.
  91172. */
  91173. var EffectLayer = /** @class */ (function () {
  91174. /**
  91175. * Instantiates a new effect Layer and references it in the scene.
  91176. * @param name The name of the layer
  91177. * @param scene The scene to use the layer in
  91178. */
  91179. function EffectLayer(
  91180. /** The Friendly of the effect in the scene */
  91181. name, scene) {
  91182. this._vertexBuffers = {};
  91183. this._maxSize = 0;
  91184. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91185. this._shouldRender = true;
  91186. this._postProcesses = [];
  91187. this._textures = [];
  91188. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91189. /**
  91190. * The clear color of the texture used to generate the glow map.
  91191. */
  91192. this.neutralColor = new BABYLON.Color4();
  91193. /**
  91194. * Specifies wether the highlight layer is enabled or not.
  91195. */
  91196. this.isEnabled = true;
  91197. /**
  91198. * An event triggered when the effect layer has been disposed.
  91199. */
  91200. this.onDisposeObservable = new BABYLON.Observable();
  91201. /**
  91202. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91203. */
  91204. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91205. /**
  91206. * An event triggered when the generated texture is being merged in the scene.
  91207. */
  91208. this.onBeforeComposeObservable = new BABYLON.Observable();
  91209. /**
  91210. * An event triggered when the generated texture has been merged in the scene.
  91211. */
  91212. this.onAfterComposeObservable = new BABYLON.Observable();
  91213. /**
  91214. * An event triggered when the efffect layer changes its size.
  91215. */
  91216. this.onSizeChangedObservable = new BABYLON.Observable();
  91217. this.name = name;
  91218. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91219. this._engine = scene.getEngine();
  91220. this._maxSize = this._engine.getCaps().maxTextureSize;
  91221. this._scene.effectLayers.push(this);
  91222. // Generate Buffers
  91223. this._generateIndexBuffer();
  91224. this._genrateVertexBuffer();
  91225. }
  91226. Object.defineProperty(EffectLayer.prototype, "camera", {
  91227. /**
  91228. * Gets the camera attached to the layer.
  91229. */
  91230. get: function () {
  91231. return this._effectLayerOptions.camera;
  91232. },
  91233. enumerable: true,
  91234. configurable: true
  91235. });
  91236. /**
  91237. * Initializes the effect layer with the required options.
  91238. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91239. */
  91240. EffectLayer.prototype._init = function (options) {
  91241. // Adapt options
  91242. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91243. this._setMainTextureSize();
  91244. this._createMainTexture();
  91245. this._createTextureAndPostProcesses();
  91246. this._mergeEffect = this._createMergeEffect();
  91247. };
  91248. /**
  91249. * Generates the index buffer of the full screen quad blending to the main canvas.
  91250. */
  91251. EffectLayer.prototype._generateIndexBuffer = function () {
  91252. // Indices
  91253. var indices = [];
  91254. indices.push(0);
  91255. indices.push(1);
  91256. indices.push(2);
  91257. indices.push(0);
  91258. indices.push(2);
  91259. indices.push(3);
  91260. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91261. };
  91262. /**
  91263. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91264. */
  91265. EffectLayer.prototype._genrateVertexBuffer = function () {
  91266. // VBO
  91267. var vertices = [];
  91268. vertices.push(1, 1);
  91269. vertices.push(-1, 1);
  91270. vertices.push(-1, -1);
  91271. vertices.push(1, -1);
  91272. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91273. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91274. };
  91275. /**
  91276. * Sets the main texture desired size which is the closest power of two
  91277. * of the engine canvas size.
  91278. */
  91279. EffectLayer.prototype._setMainTextureSize = function () {
  91280. if (this._effectLayerOptions.mainTextureFixedSize) {
  91281. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91282. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91283. }
  91284. else {
  91285. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91286. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91287. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91288. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91289. }
  91290. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91291. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91292. };
  91293. /**
  91294. * Creates the main texture for the effect layer.
  91295. */
  91296. EffectLayer.prototype._createMainTexture = function () {
  91297. var _this = this;
  91298. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91299. width: this._mainTextureDesiredSize.width,
  91300. height: this._mainTextureDesiredSize.height
  91301. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91302. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91303. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91304. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91305. this._mainTexture.anisotropicFilteringLevel = 1;
  91306. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91307. this._mainTexture.renderParticles = false;
  91308. this._mainTexture.renderList = null;
  91309. this._mainTexture.ignoreCameraViewport = true;
  91310. // Custom render function
  91311. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91312. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91313. var index;
  91314. var engine = _this._scene.getEngine();
  91315. if (depthOnlySubMeshes.length) {
  91316. engine.setColorWrite(false);
  91317. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91318. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91319. }
  91320. engine.setColorWrite(true);
  91321. }
  91322. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91323. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91324. }
  91325. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91326. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91327. }
  91328. for (index = 0; index < transparentSubMeshes.length; index++) {
  91329. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91330. }
  91331. };
  91332. this._mainTexture.onClearObservable.add(function (engine) {
  91333. engine.clear(_this.neutralColor, true, true, true);
  91334. });
  91335. };
  91336. /**
  91337. * Checks for the readiness of the element composing the layer.
  91338. * @param subMesh the mesh to check for
  91339. * @param useInstances specify wether or not to use instances to render the mesh
  91340. * @param emissiveTexture the associated emissive texture used to generate the glow
  91341. * @return true if ready otherwise, false
  91342. */
  91343. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91344. var material = subMesh.getMaterial();
  91345. if (!material) {
  91346. return false;
  91347. }
  91348. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91349. return false;
  91350. }
  91351. var defines = [];
  91352. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91353. var mesh = subMesh.getMesh();
  91354. var uv1 = false;
  91355. var uv2 = false;
  91356. // Alpha test
  91357. if (material && material.needAlphaTesting()) {
  91358. var alphaTexture = material.getAlphaTestTexture();
  91359. if (alphaTexture) {
  91360. defines.push("#define ALPHATEST");
  91361. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91362. alphaTexture.coordinatesIndex === 1) {
  91363. defines.push("#define DIFFUSEUV2");
  91364. uv2 = true;
  91365. }
  91366. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91367. defines.push("#define DIFFUSEUV1");
  91368. uv1 = true;
  91369. }
  91370. }
  91371. }
  91372. // Emissive
  91373. if (emissiveTexture) {
  91374. defines.push("#define EMISSIVE");
  91375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91376. emissiveTexture.coordinatesIndex === 1) {
  91377. defines.push("#define EMISSIVEUV2");
  91378. uv2 = true;
  91379. }
  91380. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91381. defines.push("#define EMISSIVEUV1");
  91382. uv1 = true;
  91383. }
  91384. }
  91385. if (uv1) {
  91386. attribs.push(BABYLON.VertexBuffer.UVKind);
  91387. defines.push("#define UV1");
  91388. }
  91389. if (uv2) {
  91390. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91391. defines.push("#define UV2");
  91392. }
  91393. // Bones
  91394. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91395. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91396. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91397. if (mesh.numBoneInfluencers > 4) {
  91398. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91399. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91400. }
  91401. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91402. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91403. }
  91404. else {
  91405. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91406. }
  91407. // Morph targets
  91408. var manager = mesh.morphTargetManager;
  91409. var morphInfluencers = 0;
  91410. if (manager) {
  91411. if (manager.numInfluencers > 0) {
  91412. defines.push("#define MORPHTARGETS");
  91413. morphInfluencers = manager.numInfluencers;
  91414. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91415. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91416. }
  91417. }
  91418. // Instances
  91419. if (useInstances) {
  91420. defines.push("#define INSTANCES");
  91421. attribs.push("world0");
  91422. attribs.push("world1");
  91423. attribs.push("world2");
  91424. attribs.push("world3");
  91425. }
  91426. // Get correct effect
  91427. var join = defines.join("\n");
  91428. if (this._cachedDefines !== join) {
  91429. this._cachedDefines = join;
  91430. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91431. }
  91432. return this._effectLayerMapGenerationEffect.isReady();
  91433. };
  91434. /**
  91435. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91436. */
  91437. EffectLayer.prototype.render = function () {
  91438. var currentEffect = this._mergeEffect;
  91439. // Check
  91440. if (!currentEffect.isReady())
  91441. return;
  91442. for (var i = 0; i < this._postProcesses.length; i++) {
  91443. if (!this._postProcesses[i].isReady()) {
  91444. return;
  91445. }
  91446. }
  91447. var engine = this._scene.getEngine();
  91448. this.onBeforeComposeObservable.notifyObservers(this);
  91449. // Render
  91450. engine.enableEffect(currentEffect);
  91451. engine.setState(false);
  91452. // VBOs
  91453. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91454. // Cache
  91455. var previousAlphaMode = engine.getAlphaMode();
  91456. // Go Blend.
  91457. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91458. // Blends the map on the main canvas.
  91459. this._internalRender(currentEffect);
  91460. // Restore Alpha
  91461. engine.setAlphaMode(previousAlphaMode);
  91462. this.onAfterComposeObservable.notifyObservers(this);
  91463. // Handle size changes.
  91464. var size = this._mainTexture.getSize();
  91465. this._setMainTextureSize();
  91466. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91467. // Recreate RTT and post processes on size change.
  91468. this.onSizeChangedObservable.notifyObservers(this);
  91469. this._disposeTextureAndPostProcesses();
  91470. this._createMainTexture();
  91471. this._createTextureAndPostProcesses();
  91472. }
  91473. };
  91474. /**
  91475. * Determine if a given mesh will be used in the current effect.
  91476. * @param mesh mesh to test
  91477. * @returns true if the mesh will be used
  91478. */
  91479. EffectLayer.prototype.hasMesh = function (mesh) {
  91480. return true;
  91481. };
  91482. /**
  91483. * Returns true if the layer contains information to display, otherwise false.
  91484. * @returns true if the glow layer should be rendered
  91485. */
  91486. EffectLayer.prototype.shouldRender = function () {
  91487. return this.isEnabled && this._shouldRender;
  91488. };
  91489. /**
  91490. * Returns true if the mesh should render, otherwise false.
  91491. * @param mesh The mesh to render
  91492. * @returns true if it should render otherwise false
  91493. */
  91494. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91495. return true;
  91496. };
  91497. /**
  91498. * Returns true if the mesh should render, otherwise false.
  91499. * @param mesh The mesh to render
  91500. * @returns true if it should render otherwise false
  91501. */
  91502. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91503. return true;
  91504. };
  91505. /**
  91506. * Renders the submesh passed in parameter to the generation map.
  91507. */
  91508. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91509. var _this = this;
  91510. if (!this.shouldRender()) {
  91511. return;
  91512. }
  91513. var material = subMesh.getMaterial();
  91514. var mesh = subMesh.getRenderingMesh();
  91515. var scene = this._scene;
  91516. var engine = scene.getEngine();
  91517. if (!material) {
  91518. return;
  91519. }
  91520. // Do not block in blend mode.
  91521. if (material.needAlphaBlendingForMesh(mesh)) {
  91522. return;
  91523. }
  91524. // Culling
  91525. engine.setState(material.backFaceCulling);
  91526. // Managing instances
  91527. var batch = mesh._getInstancesRenderList(subMesh._id);
  91528. if (batch.mustReturn) {
  91529. return;
  91530. }
  91531. // Early Exit per mesh
  91532. if (!this._shouldRenderMesh(mesh)) {
  91533. return;
  91534. }
  91535. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91536. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91537. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91538. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91539. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91540. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91541. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91542. // Alpha test
  91543. if (material && material.needAlphaTesting()) {
  91544. var alphaTexture = material.getAlphaTestTexture();
  91545. if (alphaTexture) {
  91546. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91547. var textureMatrix = alphaTexture.getTextureMatrix();
  91548. if (textureMatrix) {
  91549. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91550. }
  91551. }
  91552. }
  91553. // Glow emissive only
  91554. if (this._emissiveTextureAndColor.texture) {
  91555. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91556. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91557. }
  91558. // Bones
  91559. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91560. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91561. }
  91562. // Morph targets
  91563. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91564. // Draw
  91565. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91566. }
  91567. else {
  91568. // Need to reset refresh rate of the shadowMap
  91569. this._mainTexture.resetRefreshCounter();
  91570. }
  91571. };
  91572. /**
  91573. * Rebuild the required buffers.
  91574. * @hidden Internal use only.
  91575. */
  91576. EffectLayer.prototype._rebuild = function () {
  91577. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91578. if (vb) {
  91579. vb._rebuild();
  91580. }
  91581. this._generateIndexBuffer();
  91582. };
  91583. /**
  91584. * Dispose only the render target textures and post process.
  91585. */
  91586. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91587. this._mainTexture.dispose();
  91588. for (var i = 0; i < this._postProcesses.length; i++) {
  91589. if (this._postProcesses[i]) {
  91590. this._postProcesses[i].dispose();
  91591. }
  91592. }
  91593. this._postProcesses = [];
  91594. for (var i = 0; i < this._textures.length; i++) {
  91595. if (this._textures[i]) {
  91596. this._textures[i].dispose();
  91597. }
  91598. }
  91599. this._textures = [];
  91600. };
  91601. /**
  91602. * Dispose the highlight layer and free resources.
  91603. */
  91604. EffectLayer.prototype.dispose = function () {
  91605. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91606. if (vertexBuffer) {
  91607. vertexBuffer.dispose();
  91608. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91609. }
  91610. if (this._indexBuffer) {
  91611. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91612. this._indexBuffer = null;
  91613. }
  91614. // Clean textures and post processes
  91615. this._disposeTextureAndPostProcesses();
  91616. // Remove from scene
  91617. var index = this._scene.effectLayers.indexOf(this, 0);
  91618. if (index > -1) {
  91619. this._scene.effectLayers.splice(index, 1);
  91620. }
  91621. // Callback
  91622. this.onDisposeObservable.notifyObservers(this);
  91623. this.onDisposeObservable.clear();
  91624. this.onBeforeRenderMainTextureObservable.clear();
  91625. this.onBeforeComposeObservable.clear();
  91626. this.onAfterComposeObservable.clear();
  91627. this.onSizeChangedObservable.clear();
  91628. };
  91629. /**
  91630. * Gets the class name of the effect layer
  91631. * @returns the string with the class name of the effect layer
  91632. */
  91633. EffectLayer.prototype.getClassName = function () {
  91634. return "EffectLayer";
  91635. };
  91636. /**
  91637. * Creates an effect layer from parsed effect layer data
  91638. * @param parsedEffectLayer defines effect layer data
  91639. * @param scene defines the current scene
  91640. * @param rootUrl defines the root URL containing the effect layer information
  91641. * @returns a parsed effect Layer
  91642. */
  91643. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91644. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91645. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91646. };
  91647. __decorate([
  91648. BABYLON.serialize()
  91649. ], EffectLayer.prototype, "name", void 0);
  91650. __decorate([
  91651. BABYLON.serializeAsColor4()
  91652. ], EffectLayer.prototype, "neutralColor", void 0);
  91653. __decorate([
  91654. BABYLON.serialize()
  91655. ], EffectLayer.prototype, "isEnabled", void 0);
  91656. __decorate([
  91657. BABYLON.serializeAsCameraReference()
  91658. ], EffectLayer.prototype, "camera", null);
  91659. return EffectLayer;
  91660. }());
  91661. BABYLON.EffectLayer = EffectLayer;
  91662. })(BABYLON || (BABYLON = {}));
  91663. //# sourceMappingURL=babylon.effectLayer.js.map
  91664. var BABYLON;
  91665. (function (BABYLON) {
  91666. /**
  91667. * Special Glow Blur post process only blurring the alpha channel
  91668. * It enforces keeping the most luminous color in the color channel.
  91669. */
  91670. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91671. __extends(GlowBlurPostProcess, _super);
  91672. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91674. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91675. _this.direction = direction;
  91676. _this.kernel = kernel;
  91677. _this.onApplyObservable.add(function (effect) {
  91678. effect.setFloat2("screenSize", _this.width, _this.height);
  91679. effect.setVector2("direction", _this.direction);
  91680. effect.setFloat("blurWidth", _this.kernel);
  91681. });
  91682. return _this;
  91683. }
  91684. return GlowBlurPostProcess;
  91685. }(BABYLON.PostProcess));
  91686. /**
  91687. * The highlight layer Helps adding a glow effect around a mesh.
  91688. *
  91689. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91690. * glowy meshes to your scene.
  91691. *
  91692. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91693. */
  91694. var HighlightLayer = /** @class */ (function (_super) {
  91695. __extends(HighlightLayer, _super);
  91696. /**
  91697. * Instantiates a new highlight Layer and references it to the scene..
  91698. * @param name The name of the layer
  91699. * @param scene The scene to use the layer in
  91700. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91701. */
  91702. function HighlightLayer(name, scene, options) {
  91703. var _this = _super.call(this, name, scene) || this;
  91704. _this.name = name;
  91705. /**
  91706. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91707. */
  91708. _this.innerGlow = true;
  91709. /**
  91710. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91711. */
  91712. _this.outerGlow = true;
  91713. /**
  91714. * An event triggered when the highlight layer is being blurred.
  91715. */
  91716. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91717. /**
  91718. * An event triggered when the highlight layer has been blurred.
  91719. */
  91720. _this.onAfterBlurObservable = new BABYLON.Observable();
  91721. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91722. _this._meshes = {};
  91723. _this._excludedMeshes = {};
  91724. _this.neutralColor = HighlightLayer.NeutralColor;
  91725. // Warn on stencil
  91726. if (!_this._engine.isStencilEnable) {
  91727. 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 }");
  91728. }
  91729. // Adapt options
  91730. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91731. // Initialize the layer
  91732. _this._init({
  91733. alphaBlendingMode: _this._options.alphaBlendingMode,
  91734. camera: _this._options.camera,
  91735. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91736. mainTextureRatio: _this._options.mainTextureRatio
  91737. });
  91738. // Do not render as long as no meshes have been added
  91739. _this._shouldRender = false;
  91740. return _this;
  91741. }
  91742. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91743. /**
  91744. * Gets the horizontal size of the blur.
  91745. */
  91746. get: function () {
  91747. return this._horizontalBlurPostprocess.kernel;
  91748. },
  91749. /**
  91750. * Specifies the horizontal size of the blur.
  91751. */
  91752. set: function (value) {
  91753. this._horizontalBlurPostprocess.kernel = value;
  91754. },
  91755. enumerable: true,
  91756. configurable: true
  91757. });
  91758. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91759. /**
  91760. * Gets the vertical size of the blur.
  91761. */
  91762. get: function () {
  91763. return this._verticalBlurPostprocess.kernel;
  91764. },
  91765. /**
  91766. * Specifies the vertical size of the blur.
  91767. */
  91768. set: function (value) {
  91769. this._verticalBlurPostprocess.kernel = value;
  91770. },
  91771. enumerable: true,
  91772. configurable: true
  91773. });
  91774. /**
  91775. * Get the effect name of the layer.
  91776. * @return The effect name
  91777. */
  91778. HighlightLayer.prototype.getEffectName = function () {
  91779. return HighlightLayer.EffectName;
  91780. };
  91781. /**
  91782. * Create the merge effect. This is the shader use to blit the information back
  91783. * to the main canvas at the end of the scene rendering.
  91784. */
  91785. HighlightLayer.prototype._createMergeEffect = function () {
  91786. // Effect
  91787. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91788. };
  91789. /**
  91790. * Creates the render target textures and post processes used in the highlight layer.
  91791. */
  91792. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91793. var _this = this;
  91794. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91795. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91796. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91797. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91798. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91799. width: blurTextureWidth,
  91800. height: blurTextureHeight
  91801. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91802. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91803. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91804. this._blurTexture.anisotropicFilteringLevel = 16;
  91805. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91806. this._blurTexture.renderParticles = false;
  91807. this._blurTexture.ignoreCameraViewport = true;
  91808. this._textures = [this._blurTexture];
  91809. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91810. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91811. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91812. effect.setTexture("textureSampler", _this._mainTexture);
  91813. });
  91814. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91815. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91816. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91817. });
  91818. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91819. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91820. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91821. });
  91822. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91823. }
  91824. else {
  91825. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91826. width: blurTextureWidth,
  91827. height: blurTextureHeight
  91828. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91829. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91830. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91831. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91832. effect.setTexture("textureSampler", _this._mainTexture);
  91833. });
  91834. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91835. width: blurTextureWidth,
  91836. height: blurTextureHeight
  91837. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91838. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91839. }
  91840. this._mainTexture.onAfterUnbindObservable.add(function () {
  91841. _this.onBeforeBlurObservable.notifyObservers(_this);
  91842. var internalTexture = _this._blurTexture.getInternalTexture();
  91843. if (internalTexture) {
  91844. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91845. }
  91846. _this.onAfterBlurObservable.notifyObservers(_this);
  91847. });
  91848. // Prevent autoClear.
  91849. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91850. };
  91851. /**
  91852. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91853. */
  91854. HighlightLayer.prototype.needStencil = function () {
  91855. return true;
  91856. };
  91857. /**
  91858. * Checks for the readiness of the element composing the layer.
  91859. * @param subMesh the mesh to check for
  91860. * @param useInstances specify wether or not to use instances to render the mesh
  91861. * @param emissiveTexture the associated emissive texture used to generate the glow
  91862. * @return true if ready otherwise, false
  91863. */
  91864. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91865. var material = subMesh.getMaterial();
  91866. var mesh = subMesh.getRenderingMesh();
  91867. if (!material || !mesh || !this._meshes) {
  91868. return false;
  91869. }
  91870. var emissiveTexture = null;
  91871. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91872. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91873. emissiveTexture = material.emissiveTexture;
  91874. }
  91875. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91876. };
  91877. /**
  91878. * Implementation specific of rendering the generating effect on the main canvas.
  91879. * @param effect The effect used to render through
  91880. */
  91881. HighlightLayer.prototype._internalRender = function (effect) {
  91882. // Texture
  91883. effect.setTexture("textureSampler", this._blurTexture);
  91884. // Cache
  91885. var engine = this._engine;
  91886. var previousStencilBuffer = engine.getStencilBuffer();
  91887. var previousStencilFunction = engine.getStencilFunction();
  91888. var previousStencilMask = engine.getStencilMask();
  91889. var previousStencilOperationPass = engine.getStencilOperationPass();
  91890. var previousStencilOperationFail = engine.getStencilOperationFail();
  91891. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91892. var previousStencilReference = engine.getStencilFunctionReference();
  91893. // Stencil operations
  91894. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91895. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91896. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91897. // Draw order
  91898. engine.setStencilMask(0x00);
  91899. engine.setStencilBuffer(true);
  91900. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91901. // 2 passes inner outer
  91902. if (this.outerGlow) {
  91903. effect.setFloat("offset", 0);
  91904. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91905. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91906. }
  91907. if (this.innerGlow) {
  91908. effect.setFloat("offset", 1);
  91909. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91910. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91911. }
  91912. // Restore Cache
  91913. engine.setStencilFunction(previousStencilFunction);
  91914. engine.setStencilMask(previousStencilMask);
  91915. engine.setStencilBuffer(previousStencilBuffer);
  91916. engine.setStencilOperationPass(previousStencilOperationPass);
  91917. engine.setStencilOperationFail(previousStencilOperationFail);
  91918. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91919. engine.setStencilFunctionReference(previousStencilReference);
  91920. };
  91921. /**
  91922. * Returns true if the layer contains information to display, otherwise false.
  91923. */
  91924. HighlightLayer.prototype.shouldRender = function () {
  91925. if (_super.prototype.shouldRender.call(this)) {
  91926. return this._meshes ? true : false;
  91927. }
  91928. return false;
  91929. };
  91930. /**
  91931. * Returns true if the mesh should render, otherwise false.
  91932. * @param mesh The mesh to render
  91933. * @returns true if it should render otherwise false
  91934. */
  91935. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91936. // Excluded Mesh
  91937. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91938. return false;
  91939. }
  91940. ;
  91941. return true;
  91942. };
  91943. /**
  91944. * Sets the required values for both the emissive texture and and the main color.
  91945. */
  91946. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91947. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91948. if (highlightLayerMesh) {
  91949. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91950. }
  91951. else {
  91952. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91953. }
  91954. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91955. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91956. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91957. }
  91958. else {
  91959. this._emissiveTextureAndColor.texture = null;
  91960. }
  91961. };
  91962. /**
  91963. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91964. * @param mesh The mesh to exclude from the highlight layer
  91965. */
  91966. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91967. if (!this._excludedMeshes) {
  91968. return;
  91969. }
  91970. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91971. if (!meshExcluded) {
  91972. this._excludedMeshes[mesh.uniqueId] = {
  91973. mesh: mesh,
  91974. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91975. mesh.getEngine().setStencilBuffer(false);
  91976. }),
  91977. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91978. mesh.getEngine().setStencilBuffer(true);
  91979. }),
  91980. };
  91981. }
  91982. };
  91983. /**
  91984. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91985. * @param mesh The mesh to highlight
  91986. */
  91987. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91988. if (!this._excludedMeshes) {
  91989. return;
  91990. }
  91991. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91992. if (meshExcluded) {
  91993. if (meshExcluded.beforeRender) {
  91994. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91995. }
  91996. if (meshExcluded.afterRender) {
  91997. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91998. }
  91999. }
  92000. this._excludedMeshes[mesh.uniqueId] = null;
  92001. };
  92002. /**
  92003. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92004. * @param mesh mesh to test
  92005. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92006. */
  92007. HighlightLayer.prototype.hasMesh = function (mesh) {
  92008. if (!this._meshes) {
  92009. return false;
  92010. }
  92011. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92012. };
  92013. /**
  92014. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92015. * @param mesh The mesh to highlight
  92016. * @param color The color of the highlight
  92017. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92018. */
  92019. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92020. var _this = this;
  92021. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92022. if (!this._meshes) {
  92023. return;
  92024. }
  92025. var meshHighlight = this._meshes[mesh.uniqueId];
  92026. if (meshHighlight) {
  92027. meshHighlight.color = color;
  92028. }
  92029. else {
  92030. this._meshes[mesh.uniqueId] = {
  92031. mesh: mesh,
  92032. color: color,
  92033. // Lambda required for capture due to Observable this context
  92034. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92035. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92036. _this._defaultStencilReference(mesh);
  92037. }
  92038. else {
  92039. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92040. }
  92041. }),
  92042. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92043. glowEmissiveOnly: glowEmissiveOnly
  92044. };
  92045. }
  92046. this._shouldRender = true;
  92047. };
  92048. /**
  92049. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92050. * @param mesh The mesh to highlight
  92051. */
  92052. HighlightLayer.prototype.removeMesh = function (mesh) {
  92053. if (!this._meshes) {
  92054. return;
  92055. }
  92056. var meshHighlight = this._meshes[mesh.uniqueId];
  92057. if (meshHighlight) {
  92058. if (meshHighlight.observerHighlight) {
  92059. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92060. }
  92061. if (meshHighlight.observerDefault) {
  92062. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92063. }
  92064. delete this._meshes[mesh.uniqueId];
  92065. }
  92066. this._shouldRender = false;
  92067. for (var meshHighlightToCheck in this._meshes) {
  92068. if (this._meshes[meshHighlightToCheck]) {
  92069. this._shouldRender = true;
  92070. break;
  92071. }
  92072. }
  92073. };
  92074. /**
  92075. * Force the stencil to the normal expected value for none glowing parts
  92076. */
  92077. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92078. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92079. };
  92080. /**
  92081. * Free any resources and references associated to a mesh.
  92082. * Internal use
  92083. * @param mesh The mesh to free.
  92084. */
  92085. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92086. this.removeMesh(mesh);
  92087. this.removeExcludedMesh(mesh);
  92088. };
  92089. /**
  92090. * Dispose the highlight layer and free resources.
  92091. */
  92092. HighlightLayer.prototype.dispose = function () {
  92093. if (this._meshes) {
  92094. // Clean mesh references
  92095. for (var id in this._meshes) {
  92096. var meshHighlight = this._meshes[id];
  92097. if (meshHighlight && meshHighlight.mesh) {
  92098. if (meshHighlight.observerHighlight) {
  92099. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92100. }
  92101. if (meshHighlight.observerDefault) {
  92102. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92103. }
  92104. }
  92105. }
  92106. this._meshes = null;
  92107. }
  92108. if (this._excludedMeshes) {
  92109. for (var id in this._excludedMeshes) {
  92110. var meshHighlight = this._excludedMeshes[id];
  92111. if (meshHighlight) {
  92112. if (meshHighlight.beforeRender) {
  92113. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92114. }
  92115. if (meshHighlight.afterRender) {
  92116. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92117. }
  92118. }
  92119. }
  92120. this._excludedMeshes = null;
  92121. }
  92122. _super.prototype.dispose.call(this);
  92123. };
  92124. /**
  92125. * Gets the class name of the effect layer
  92126. * @returns the string with the class name of the effect layer
  92127. */
  92128. HighlightLayer.prototype.getClassName = function () {
  92129. return "HighlightLayer";
  92130. };
  92131. /**
  92132. * Serializes this Highlight layer
  92133. * @returns a serialized Highlight layer object
  92134. */
  92135. HighlightLayer.prototype.serialize = function () {
  92136. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92137. serializationObject.customType = "BABYLON.HighlightLayer";
  92138. // Highlighted meshes
  92139. serializationObject.meshes = [];
  92140. if (this._meshes) {
  92141. for (var m in this._meshes) {
  92142. var mesh = this._meshes[m];
  92143. if (mesh) {
  92144. serializationObject.meshes.push({
  92145. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92146. color: mesh.color.asArray(),
  92147. meshId: mesh.mesh.id
  92148. });
  92149. }
  92150. }
  92151. }
  92152. // Excluded meshes
  92153. serializationObject.excludedMeshes = [];
  92154. if (this._excludedMeshes) {
  92155. for (var e in this._excludedMeshes) {
  92156. var excludedMesh = this._excludedMeshes[e];
  92157. if (excludedMesh) {
  92158. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92159. }
  92160. }
  92161. }
  92162. return serializationObject;
  92163. };
  92164. /**
  92165. * Creates a Highlight layer from parsed Highlight layer data
  92166. * @param parsedHightlightLayer defines the Highlight layer data
  92167. * @param scene defines the current scene
  92168. * @param rootUrl defines the root URL containing the Highlight layer information
  92169. * @returns a parsed Highlight layer
  92170. */
  92171. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92172. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92173. var index;
  92174. // Excluded meshes
  92175. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92176. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92177. if (mesh) {
  92178. hl.addExcludedMesh(mesh);
  92179. }
  92180. }
  92181. // Included meshes
  92182. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92183. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92184. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92185. if (mesh) {
  92186. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92187. }
  92188. }
  92189. return hl;
  92190. };
  92191. /**
  92192. * Effect Name of the highlight layer.
  92193. */
  92194. HighlightLayer.EffectName = "HighlightLayer";
  92195. /**
  92196. * The neutral color used during the preparation of the glow effect.
  92197. * This is black by default as the blend operation is a blend operation.
  92198. */
  92199. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92200. /**
  92201. * Stencil value used for glowing meshes.
  92202. */
  92203. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92204. /**
  92205. * Stencil value used for the other meshes in the scene.
  92206. */
  92207. HighlightLayer.NormalMeshStencilReference = 0x01;
  92208. __decorate([
  92209. BABYLON.serialize()
  92210. ], HighlightLayer.prototype, "innerGlow", void 0);
  92211. __decorate([
  92212. BABYLON.serialize()
  92213. ], HighlightLayer.prototype, "outerGlow", void 0);
  92214. __decorate([
  92215. BABYLON.serialize()
  92216. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92217. __decorate([
  92218. BABYLON.serialize()
  92219. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92220. __decorate([
  92221. BABYLON.serialize("options")
  92222. ], HighlightLayer.prototype, "_options", void 0);
  92223. return HighlightLayer;
  92224. }(BABYLON.EffectLayer));
  92225. BABYLON.HighlightLayer = HighlightLayer;
  92226. })(BABYLON || (BABYLON = {}));
  92227. //# sourceMappingURL=babylon.highlightLayer.js.map
  92228. var BABYLON;
  92229. (function (BABYLON) {
  92230. /**
  92231. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92232. *
  92233. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92234. * glowy meshes to your scene.
  92235. *
  92236. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92237. */
  92238. var GlowLayer = /** @class */ (function (_super) {
  92239. __extends(GlowLayer, _super);
  92240. /**
  92241. * Instantiates a new glow Layer and references it to the scene.
  92242. * @param name The name of the layer
  92243. * @param scene The scene to use the layer in
  92244. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92245. */
  92246. function GlowLayer(name, scene, options) {
  92247. var _this = _super.call(this, name, scene) || this;
  92248. _this._intensity = 1.0;
  92249. _this._includedOnlyMeshes = [];
  92250. _this._excludedMeshes = [];
  92251. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92252. // Adapt options
  92253. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92254. // Initialize the layer
  92255. _this._init({
  92256. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92257. camera: _this._options.camera,
  92258. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92259. mainTextureRatio: _this._options.mainTextureRatio
  92260. });
  92261. return _this;
  92262. }
  92263. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92264. /**
  92265. * Gets the kernel size of the blur.
  92266. */
  92267. get: function () {
  92268. return this._horizontalBlurPostprocess1.kernel;
  92269. },
  92270. /**
  92271. * Sets the kernel size of the blur.
  92272. */
  92273. set: function (value) {
  92274. this._horizontalBlurPostprocess1.kernel = value;
  92275. this._verticalBlurPostprocess1.kernel = value;
  92276. this._horizontalBlurPostprocess2.kernel = value;
  92277. this._verticalBlurPostprocess2.kernel = value;
  92278. },
  92279. enumerable: true,
  92280. configurable: true
  92281. });
  92282. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92283. /**
  92284. * Gets the glow intensity.
  92285. */
  92286. get: function () {
  92287. return this._intensity;
  92288. },
  92289. /**
  92290. * Sets the glow intensity.
  92291. */
  92292. set: function (value) {
  92293. this._intensity = value;
  92294. },
  92295. enumerable: true,
  92296. configurable: true
  92297. });
  92298. /**
  92299. * Get the effect name of the layer.
  92300. * @return The effect name
  92301. */
  92302. GlowLayer.prototype.getEffectName = function () {
  92303. return GlowLayer.EffectName;
  92304. };
  92305. /**
  92306. * Create the merge effect. This is the shader use to blit the information back
  92307. * to the main canvas at the end of the scene rendering.
  92308. */
  92309. GlowLayer.prototype._createMergeEffect = function () {
  92310. // Effect
  92311. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92312. };
  92313. /**
  92314. * Creates the render target textures and post processes used in the glow layer.
  92315. */
  92316. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92317. var _this = this;
  92318. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92319. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92320. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92321. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92322. var textureType = 0;
  92323. if (this._engine.getCaps().textureHalfFloatRender) {
  92324. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92325. }
  92326. else {
  92327. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92328. }
  92329. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92330. width: blurTextureWidth,
  92331. height: blurTextureHeight
  92332. }, this._scene, false, true, textureType);
  92333. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92334. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92335. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92336. this._blurTexture1.renderParticles = false;
  92337. this._blurTexture1.ignoreCameraViewport = true;
  92338. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92339. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92340. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92341. width: blurTextureWidth2,
  92342. height: blurTextureHeight2
  92343. }, this._scene, false, true, textureType);
  92344. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92345. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92346. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92347. this._blurTexture2.renderParticles = false;
  92348. this._blurTexture2.ignoreCameraViewport = true;
  92349. this._textures = [this._blurTexture1, this._blurTexture2];
  92350. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92351. width: blurTextureWidth,
  92352. height: blurTextureHeight
  92353. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92354. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92355. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92356. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92357. effect.setTexture("textureSampler", _this._mainTexture);
  92358. });
  92359. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92360. width: blurTextureWidth,
  92361. height: blurTextureHeight
  92362. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92363. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92364. width: blurTextureWidth2,
  92365. height: blurTextureHeight2
  92366. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92367. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92368. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92369. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92370. effect.setTexture("textureSampler", _this._blurTexture1);
  92371. });
  92372. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92373. width: blurTextureWidth2,
  92374. height: blurTextureHeight2
  92375. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92376. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92377. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92378. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92379. this._mainTexture.samples = this._options.mainTextureSamples;
  92380. this._mainTexture.onAfterUnbindObservable.add(function () {
  92381. var internalTexture = _this._blurTexture1.getInternalTexture();
  92382. if (internalTexture) {
  92383. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92384. internalTexture = _this._blurTexture2.getInternalTexture();
  92385. if (internalTexture) {
  92386. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92387. }
  92388. }
  92389. });
  92390. // Prevent autoClear.
  92391. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92392. };
  92393. /**
  92394. * Checks for the readiness of the element composing the layer.
  92395. * @param subMesh the mesh to check for
  92396. * @param useInstances specify wether or not to use instances to render the mesh
  92397. * @param emissiveTexture the associated emissive texture used to generate the glow
  92398. * @return true if ready otherwise, false
  92399. */
  92400. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92401. var material = subMesh.getMaterial();
  92402. var mesh = subMesh.getRenderingMesh();
  92403. if (!material || !mesh) {
  92404. return false;
  92405. }
  92406. var emissiveTexture = material.emissiveTexture;
  92407. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92408. };
  92409. /**
  92410. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92411. */
  92412. GlowLayer.prototype.needStencil = function () {
  92413. return false;
  92414. };
  92415. /**
  92416. * Implementation specific of rendering the generating effect on the main canvas.
  92417. * @param effect The effect used to render through
  92418. */
  92419. GlowLayer.prototype._internalRender = function (effect) {
  92420. // Texture
  92421. effect.setTexture("textureSampler", this._blurTexture1);
  92422. effect.setTexture("textureSampler2", this._blurTexture2);
  92423. effect.setFloat("offset", this._intensity);
  92424. // Cache
  92425. var engine = this._engine;
  92426. var previousStencilBuffer = engine.getStencilBuffer();
  92427. // Draw order
  92428. engine.setStencilBuffer(false);
  92429. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92430. // Draw order
  92431. engine.setStencilBuffer(previousStencilBuffer);
  92432. };
  92433. /**
  92434. * Sets the required values for both the emissive texture and and the main color.
  92435. */
  92436. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92437. var textureLevel = 1.0;
  92438. if (this.customEmissiveTextureSelector) {
  92439. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92440. }
  92441. else {
  92442. if (material) {
  92443. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92444. if (this._emissiveTextureAndColor.texture) {
  92445. textureLevel = this._emissiveTextureAndColor.texture.level;
  92446. }
  92447. }
  92448. else {
  92449. this._emissiveTextureAndColor.texture = null;
  92450. }
  92451. }
  92452. if (this.customEmissiveColorSelector) {
  92453. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92454. }
  92455. else {
  92456. if (material.emissiveColor) {
  92457. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92458. }
  92459. else {
  92460. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92461. }
  92462. }
  92463. };
  92464. /**
  92465. * Returns true if the mesh should render, otherwise false.
  92466. * @param mesh The mesh to render
  92467. * @returns true if it should render otherwise false
  92468. */
  92469. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92470. return this.hasMesh(mesh);
  92471. };
  92472. /**
  92473. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92474. * @param mesh The mesh to exclude from the glow layer
  92475. */
  92476. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92477. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92478. this._excludedMeshes.push(mesh.uniqueId);
  92479. }
  92480. };
  92481. /**
  92482. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92483. * @param mesh The mesh to remove
  92484. */
  92485. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92486. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92487. if (index !== -1) {
  92488. this._excludedMeshes.splice(index, 1);
  92489. }
  92490. };
  92491. /**
  92492. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92493. * @param mesh The mesh to include in the glow layer
  92494. */
  92495. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92496. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92497. this._includedOnlyMeshes.push(mesh.uniqueId);
  92498. }
  92499. };
  92500. /**
  92501. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92502. * @param mesh The mesh to remove
  92503. */
  92504. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92505. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92506. if (index !== -1) {
  92507. this._includedOnlyMeshes.splice(index, 1);
  92508. }
  92509. };
  92510. /**
  92511. * Determine if a given mesh will be used in the glow layer
  92512. * @param mesh The mesh to test
  92513. * @returns true if the mesh will be highlighted by the current glow layer
  92514. */
  92515. GlowLayer.prototype.hasMesh = function (mesh) {
  92516. // Included Mesh
  92517. if (this._includedOnlyMeshes.length) {
  92518. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92519. }
  92520. ;
  92521. // Excluded Mesh
  92522. if (this._excludedMeshes.length) {
  92523. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92524. }
  92525. ;
  92526. return true;
  92527. };
  92528. /**
  92529. * Free any resources and references associated to a mesh.
  92530. * Internal use
  92531. * @param mesh The mesh to free.
  92532. */
  92533. GlowLayer.prototype._disposeMesh = function (mesh) {
  92534. this.removeIncludedOnlyMesh(mesh);
  92535. this.removeExcludedMesh(mesh);
  92536. };
  92537. /**
  92538. * Gets the class name of the effect layer
  92539. * @returns the string with the class name of the effect layer
  92540. */
  92541. GlowLayer.prototype.getClassName = function () {
  92542. return "GlowLayer";
  92543. };
  92544. /**
  92545. * Serializes this glow layer
  92546. * @returns a serialized glow layer object
  92547. */
  92548. GlowLayer.prototype.serialize = function () {
  92549. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92550. serializationObject.customType = "BABYLON.GlowLayer";
  92551. var index;
  92552. // Included meshes
  92553. serializationObject.includedMeshes = [];
  92554. if (this._includedOnlyMeshes.length) {
  92555. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92556. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92557. if (mesh) {
  92558. serializationObject.includedMeshes.push(mesh.id);
  92559. }
  92560. }
  92561. }
  92562. // Excluded meshes
  92563. serializationObject.excludedMeshes = [];
  92564. if (this._excludedMeshes.length) {
  92565. for (index = 0; index < this._excludedMeshes.length; index++) {
  92566. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92567. if (mesh) {
  92568. serializationObject.excludedMeshes.push(mesh.id);
  92569. }
  92570. }
  92571. }
  92572. return serializationObject;
  92573. };
  92574. /**
  92575. * Creates a Glow Layer from parsed glow layer data
  92576. * @param parsedGlowLayer defines glow layer data
  92577. * @param scene defines the current scene
  92578. * @param rootUrl defines the root URL containing the glow layer information
  92579. * @returns a parsed Glow Layer
  92580. */
  92581. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92582. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92583. var index;
  92584. // Excluded meshes
  92585. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92586. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92587. if (mesh) {
  92588. gl.addExcludedMesh(mesh);
  92589. }
  92590. }
  92591. // Included meshes
  92592. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92593. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92594. if (mesh) {
  92595. gl.addIncludedOnlyMesh(mesh);
  92596. }
  92597. }
  92598. return gl;
  92599. };
  92600. /**
  92601. * Effect Name of the layer.
  92602. */
  92603. GlowLayer.EffectName = "GlowLayer";
  92604. /**
  92605. * The default blur kernel size used for the glow.
  92606. */
  92607. GlowLayer.DefaultBlurKernelSize = 32;
  92608. /**
  92609. * The default texture size ratio used for the glow.
  92610. */
  92611. GlowLayer.DefaultTextureRatio = 0.5;
  92612. __decorate([
  92613. BABYLON.serialize()
  92614. ], GlowLayer.prototype, "blurKernelSize", null);
  92615. __decorate([
  92616. BABYLON.serialize()
  92617. ], GlowLayer.prototype, "intensity", null);
  92618. __decorate([
  92619. BABYLON.serialize("options")
  92620. ], GlowLayer.prototype, "_options", void 0);
  92621. return GlowLayer;
  92622. }(BABYLON.EffectLayer));
  92623. BABYLON.GlowLayer = GlowLayer;
  92624. })(BABYLON || (BABYLON = {}));
  92625. //# sourceMappingURL=babylon.glowLayer.js.map
  92626. var BABYLON;
  92627. (function (BABYLON) {
  92628. /**
  92629. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92630. */
  92631. var AssetTaskState;
  92632. (function (AssetTaskState) {
  92633. /**
  92634. * Initialization
  92635. */
  92636. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92637. /**
  92638. * Running
  92639. */
  92640. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92641. /**
  92642. * Done
  92643. */
  92644. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92645. /**
  92646. * Error
  92647. */
  92648. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92649. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92650. /**
  92651. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92652. */
  92653. var AbstractAssetTask = /** @class */ (function () {
  92654. /**
  92655. * Creates a new {BABYLON.AssetsManager}
  92656. * @param name defines the name of the task
  92657. */
  92658. function AbstractAssetTask(
  92659. /**
  92660. * Task name
  92661. */ name) {
  92662. this.name = name;
  92663. this._isCompleted = false;
  92664. this._taskState = AssetTaskState.INIT;
  92665. }
  92666. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92667. /**
  92668. * Get if the task is completed
  92669. */
  92670. get: function () {
  92671. return this._isCompleted;
  92672. },
  92673. enumerable: true,
  92674. configurable: true
  92675. });
  92676. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92677. /**
  92678. * Gets the current state of the task
  92679. */
  92680. get: function () {
  92681. return this._taskState;
  92682. },
  92683. enumerable: true,
  92684. configurable: true
  92685. });
  92686. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92687. /**
  92688. * Gets the current error object (if task is in error)
  92689. */
  92690. get: function () {
  92691. return this._errorObject;
  92692. },
  92693. enumerable: true,
  92694. configurable: true
  92695. });
  92696. /**
  92697. * Internal only
  92698. * @hidden
  92699. */
  92700. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92701. if (this._errorObject) {
  92702. return;
  92703. }
  92704. this._errorObject = {
  92705. message: message,
  92706. exception: exception
  92707. };
  92708. };
  92709. /**
  92710. * Execute the current task
  92711. * @param scene defines the scene where you want your assets to be loaded
  92712. * @param onSuccess is a callback called when the task is successfully executed
  92713. * @param onError is a callback called if an error occurs
  92714. */
  92715. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92716. var _this = this;
  92717. this._taskState = AssetTaskState.RUNNING;
  92718. this.runTask(scene, function () {
  92719. _this.onDoneCallback(onSuccess, onError);
  92720. }, function (msg, exception) {
  92721. _this.onErrorCallback(onError, msg, exception);
  92722. });
  92723. };
  92724. /**
  92725. * Execute the current task
  92726. * @param scene defines the scene where you want your assets to be loaded
  92727. * @param onSuccess is a callback called when the task is successfully executed
  92728. * @param onError is a callback called if an error occurs
  92729. */
  92730. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92731. throw new Error("runTask is not implemented");
  92732. };
  92733. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92734. this._taskState = AssetTaskState.ERROR;
  92735. this._errorObject = {
  92736. message: message,
  92737. exception: exception
  92738. };
  92739. if (this.onError) {
  92740. this.onError(this, message, exception);
  92741. }
  92742. onError();
  92743. };
  92744. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92745. try {
  92746. this._taskState = AssetTaskState.DONE;
  92747. this._isCompleted = true;
  92748. if (this.onSuccess) {
  92749. this.onSuccess(this);
  92750. }
  92751. onSuccess();
  92752. }
  92753. catch (e) {
  92754. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92755. }
  92756. };
  92757. return AbstractAssetTask;
  92758. }());
  92759. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92760. /**
  92761. * Class used to share progress information about assets loading
  92762. */
  92763. var AssetsProgressEvent = /** @class */ (function () {
  92764. /**
  92765. * Creates a {BABYLON.AssetsProgressEvent}
  92766. * @param remainingCount defines the number of remaining tasks to process
  92767. * @param totalCount defines the total number of tasks
  92768. * @param task defines the task that was just processed
  92769. */
  92770. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92771. this.remainingCount = remainingCount;
  92772. this.totalCount = totalCount;
  92773. this.task = task;
  92774. }
  92775. return AssetsProgressEvent;
  92776. }());
  92777. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92778. /**
  92779. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92780. */
  92781. var MeshAssetTask = /** @class */ (function (_super) {
  92782. __extends(MeshAssetTask, _super);
  92783. /**
  92784. * Creates a new {BABYLON.MeshAssetTask}
  92785. * @param name defines the name of the task
  92786. * @param meshesNames defines the list of mesh's names you want to load
  92787. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92788. * @param sceneFilename defines the filename of the scene to load from
  92789. */
  92790. function MeshAssetTask(
  92791. /**
  92792. * Defines the name of the task
  92793. */
  92794. name,
  92795. /**
  92796. * Defines the list of mesh's names you want to load
  92797. */
  92798. meshesNames,
  92799. /**
  92800. * Defines the root url to use as a base to load your meshes and associated resources
  92801. */
  92802. rootUrl,
  92803. /**
  92804. * Defines the filename of the scene to load from
  92805. */
  92806. sceneFilename) {
  92807. var _this = _super.call(this, name) || this;
  92808. _this.name = name;
  92809. _this.meshesNames = meshesNames;
  92810. _this.rootUrl = rootUrl;
  92811. _this.sceneFilename = sceneFilename;
  92812. return _this;
  92813. }
  92814. /**
  92815. * Execute the current task
  92816. * @param scene defines the scene where you want your assets to be loaded
  92817. * @param onSuccess is a callback called when the task is successfully executed
  92818. * @param onError is a callback called if an error occurs
  92819. */
  92820. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92821. var _this = this;
  92822. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92823. _this.loadedMeshes = meshes;
  92824. _this.loadedParticleSystems = particleSystems;
  92825. _this.loadedSkeletons = skeletons;
  92826. onSuccess();
  92827. }, null, function (scene, message, exception) {
  92828. onError(message, exception);
  92829. });
  92830. };
  92831. return MeshAssetTask;
  92832. }(AbstractAssetTask));
  92833. BABYLON.MeshAssetTask = MeshAssetTask;
  92834. /**
  92835. * Define a task used by {BABYLON.AssetsManager} to load text content
  92836. */
  92837. var TextFileAssetTask = /** @class */ (function (_super) {
  92838. __extends(TextFileAssetTask, _super);
  92839. /**
  92840. * Creates a new TextFileAssetTask object
  92841. * @param name defines the name of the task
  92842. * @param url defines the location of the file to load
  92843. */
  92844. function TextFileAssetTask(
  92845. /**
  92846. * Defines the name of the task
  92847. */
  92848. name,
  92849. /**
  92850. * Defines the location of the file to load
  92851. */
  92852. url) {
  92853. var _this = _super.call(this, name) || this;
  92854. _this.name = name;
  92855. _this.url = url;
  92856. return _this;
  92857. }
  92858. /**
  92859. * Execute the current task
  92860. * @param scene defines the scene where you want your assets to be loaded
  92861. * @param onSuccess is a callback called when the task is successfully executed
  92862. * @param onError is a callback called if an error occurs
  92863. */
  92864. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92865. var _this = this;
  92866. scene._loadFile(this.url, function (data) {
  92867. _this.text = data;
  92868. onSuccess();
  92869. }, undefined, false, false, function (request, exception) {
  92870. if (request) {
  92871. onError(request.status + " " + request.statusText, exception);
  92872. }
  92873. });
  92874. };
  92875. return TextFileAssetTask;
  92876. }(AbstractAssetTask));
  92877. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92878. /**
  92879. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92880. */
  92881. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92882. __extends(BinaryFileAssetTask, _super);
  92883. /**
  92884. * Creates a new BinaryFileAssetTask object
  92885. * @param name defines the name of the new task
  92886. * @param url defines the location of the file to load
  92887. */
  92888. function BinaryFileAssetTask(
  92889. /**
  92890. * Defines the name of the task
  92891. */
  92892. name,
  92893. /**
  92894. * Defines the location of the file to load
  92895. */
  92896. url) {
  92897. var _this = _super.call(this, name) || this;
  92898. _this.name = name;
  92899. _this.url = url;
  92900. return _this;
  92901. }
  92902. /**
  92903. * Execute the current task
  92904. * @param scene defines the scene where you want your assets to be loaded
  92905. * @param onSuccess is a callback called when the task is successfully executed
  92906. * @param onError is a callback called if an error occurs
  92907. */
  92908. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92909. var _this = this;
  92910. scene._loadFile(this.url, function (data) {
  92911. _this.data = data;
  92912. onSuccess();
  92913. }, undefined, true, true, function (request, exception) {
  92914. if (request) {
  92915. onError(request.status + " " + request.statusText, exception);
  92916. }
  92917. });
  92918. };
  92919. return BinaryFileAssetTask;
  92920. }(AbstractAssetTask));
  92921. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92922. /**
  92923. * Define a task used by {BABYLON.AssetsManager} to load images
  92924. */
  92925. var ImageAssetTask = /** @class */ (function (_super) {
  92926. __extends(ImageAssetTask, _super);
  92927. /**
  92928. * Creates a new ImageAssetTask
  92929. * @param name defines the name of the task
  92930. * @param url defines the location of the image to load
  92931. */
  92932. function ImageAssetTask(
  92933. /**
  92934. * Defines the name of the task
  92935. */
  92936. name,
  92937. /**
  92938. * Defines the location of the image to load
  92939. */
  92940. url) {
  92941. var _this = _super.call(this, name) || this;
  92942. _this.name = name;
  92943. _this.url = url;
  92944. return _this;
  92945. }
  92946. /**
  92947. * Execute the current task
  92948. * @param scene defines the scene where you want your assets to be loaded
  92949. * @param onSuccess is a callback called when the task is successfully executed
  92950. * @param onError is a callback called if an error occurs
  92951. */
  92952. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92953. var _this = this;
  92954. var img = new Image();
  92955. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92956. img.onload = function () {
  92957. _this.image = img;
  92958. onSuccess();
  92959. };
  92960. img.onerror = function (err) {
  92961. onError("Error loading image", err);
  92962. };
  92963. img.src = this.url;
  92964. };
  92965. return ImageAssetTask;
  92966. }(AbstractAssetTask));
  92967. BABYLON.ImageAssetTask = ImageAssetTask;
  92968. /**
  92969. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92970. */
  92971. var TextureAssetTask = /** @class */ (function (_super) {
  92972. __extends(TextureAssetTask, _super);
  92973. /**
  92974. * Creates a new TextureAssetTask object
  92975. * @param name defines the name of the task
  92976. * @param url defines the location of the file to load
  92977. * @param noMipmap defines if mipmap should not be generated (default is false)
  92978. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92979. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92980. */
  92981. function TextureAssetTask(
  92982. /**
  92983. * Defines the name of the task
  92984. */
  92985. name,
  92986. /**
  92987. * Defines the location of the file to load
  92988. */
  92989. url,
  92990. /**
  92991. * Defines if mipmap should not be generated (default is false)
  92992. */
  92993. noMipmap,
  92994. /**
  92995. * Defines if texture must be inverted on Y axis (default is false)
  92996. */
  92997. invertY,
  92998. /**
  92999. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93000. */
  93001. samplingMode) {
  93002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93003. var _this = _super.call(this, name) || this;
  93004. _this.name = name;
  93005. _this.url = url;
  93006. _this.noMipmap = noMipmap;
  93007. _this.invertY = invertY;
  93008. _this.samplingMode = samplingMode;
  93009. return _this;
  93010. }
  93011. /**
  93012. * Execute the current task
  93013. * @param scene defines the scene where you want your assets to be loaded
  93014. * @param onSuccess is a callback called when the task is successfully executed
  93015. * @param onError is a callback called if an error occurs
  93016. */
  93017. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93018. var onload = function () {
  93019. onSuccess();
  93020. };
  93021. var onerror = function (message, exception) {
  93022. onError(message, exception);
  93023. };
  93024. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93025. };
  93026. return TextureAssetTask;
  93027. }(AbstractAssetTask));
  93028. BABYLON.TextureAssetTask = TextureAssetTask;
  93029. /**
  93030. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93031. */
  93032. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93033. __extends(CubeTextureAssetTask, _super);
  93034. /**
  93035. * Creates a new CubeTextureAssetTask
  93036. * @param name defines the name of the task
  93037. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93038. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93039. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93040. * @param files defines the explicit list of files (undefined by default)
  93041. */
  93042. function CubeTextureAssetTask(
  93043. /**
  93044. * Defines the name of the task
  93045. */
  93046. name,
  93047. /**
  93048. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93049. */
  93050. url,
  93051. /**
  93052. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93053. */
  93054. extensions,
  93055. /**
  93056. * Defines if mipmaps should not be generated (default is false)
  93057. */
  93058. noMipmap,
  93059. /**
  93060. * Defines the explicit list of files (undefined by default)
  93061. */
  93062. files) {
  93063. var _this = _super.call(this, name) || this;
  93064. _this.name = name;
  93065. _this.url = url;
  93066. _this.extensions = extensions;
  93067. _this.noMipmap = noMipmap;
  93068. _this.files = files;
  93069. return _this;
  93070. }
  93071. /**
  93072. * Execute the current task
  93073. * @param scene defines the scene where you want your assets to be loaded
  93074. * @param onSuccess is a callback called when the task is successfully executed
  93075. * @param onError is a callback called if an error occurs
  93076. */
  93077. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93078. var onload = function () {
  93079. onSuccess();
  93080. };
  93081. var onerror = function (message, exception) {
  93082. onError(message, exception);
  93083. };
  93084. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93085. };
  93086. return CubeTextureAssetTask;
  93087. }(AbstractAssetTask));
  93088. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93089. /**
  93090. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93091. */
  93092. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93093. __extends(HDRCubeTextureAssetTask, _super);
  93094. /**
  93095. * Creates a new HDRCubeTextureAssetTask object
  93096. * @param name defines the name of the task
  93097. * @param url defines the location of the file to load
  93098. * @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.
  93099. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93100. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93101. * @param gammaSpace 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)
  93102. * @param reserved Internal use only
  93103. */
  93104. function HDRCubeTextureAssetTask(
  93105. /**
  93106. * Defines the name of the task
  93107. */
  93108. name,
  93109. /**
  93110. * Defines the location of the file to load
  93111. */
  93112. url,
  93113. /**
  93114. * Defines the desired size (the more it increases the longer the generation will be)
  93115. */
  93116. size,
  93117. /**
  93118. * Defines if mipmaps should not be generated (default is false)
  93119. */
  93120. noMipmap,
  93121. /**
  93122. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93123. */
  93124. generateHarmonics,
  93125. /**
  93126. * 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)
  93127. */
  93128. gammaSpace,
  93129. /**
  93130. * Internal Use Only
  93131. */
  93132. reserved) {
  93133. if (noMipmap === void 0) { noMipmap = false; }
  93134. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93135. if (gammaSpace === void 0) { gammaSpace = false; }
  93136. if (reserved === void 0) { reserved = false; }
  93137. var _this = _super.call(this, name) || this;
  93138. _this.name = name;
  93139. _this.url = url;
  93140. _this.size = size;
  93141. _this.noMipmap = noMipmap;
  93142. _this.generateHarmonics = generateHarmonics;
  93143. _this.gammaSpace = gammaSpace;
  93144. _this.reserved = reserved;
  93145. return _this;
  93146. }
  93147. /**
  93148. * Execute the current task
  93149. * @param scene defines the scene where you want your assets to be loaded
  93150. * @param onSuccess is a callback called when the task is successfully executed
  93151. * @param onError is a callback called if an error occurs
  93152. */
  93153. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93154. var onload = function () {
  93155. onSuccess();
  93156. };
  93157. var onerror = function (message, exception) {
  93158. onError(message, exception);
  93159. };
  93160. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93161. };
  93162. return HDRCubeTextureAssetTask;
  93163. }(AbstractAssetTask));
  93164. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93165. /**
  93166. * This class can be used to easily import assets into a scene
  93167. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93168. */
  93169. var AssetsManager = /** @class */ (function () {
  93170. /**
  93171. * Creates a new AssetsManager
  93172. * @param scene defines the scene to work on
  93173. */
  93174. function AssetsManager(scene) {
  93175. this._isLoading = false;
  93176. this._tasks = new Array();
  93177. this._waitingTasksCount = 0;
  93178. this._totalTasksCount = 0;
  93179. /**
  93180. * Observable called when all tasks are processed
  93181. */
  93182. this.onTaskSuccessObservable = new BABYLON.Observable();
  93183. /**
  93184. * Observable called when a task had an error
  93185. */
  93186. this.onTaskErrorObservable = new BABYLON.Observable();
  93187. /**
  93188. * Observable called when a task is successful
  93189. */
  93190. this.onTasksDoneObservable = new BABYLON.Observable();
  93191. /**
  93192. * Observable called when a task is done (whatever the result is)
  93193. */
  93194. this.onProgressObservable = new BABYLON.Observable();
  93195. /**
  93196. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93197. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93198. */
  93199. this.useDefaultLoadingScreen = true;
  93200. this._scene = scene;
  93201. }
  93202. /**
  93203. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93204. * @param taskName defines the name of the new task
  93205. * @param meshesNames defines the name of meshes to load
  93206. * @param rootUrl defines the root url to use to locate files
  93207. * @param sceneFilename defines the filename of the scene file
  93208. * @returns a new {BABYLON.MeshAssetTask} object
  93209. */
  93210. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93211. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93212. this._tasks.push(task);
  93213. return task;
  93214. };
  93215. /**
  93216. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93217. * @param taskName defines the name of the new task
  93218. * @param url defines the url of the file to load
  93219. * @returns a new {BABYLON.TextFileAssetTask} object
  93220. */
  93221. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93222. var task = new TextFileAssetTask(taskName, url);
  93223. this._tasks.push(task);
  93224. return task;
  93225. };
  93226. /**
  93227. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93228. * @param taskName defines the name of the new task
  93229. * @param url defines the url of the file to load
  93230. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93231. */
  93232. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93233. var task = new BinaryFileAssetTask(taskName, url);
  93234. this._tasks.push(task);
  93235. return task;
  93236. };
  93237. /**
  93238. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93239. * @param taskName defines the name of the new task
  93240. * @param url defines the url of the file to load
  93241. * @returns a new {BABYLON.ImageAssetTask} object
  93242. */
  93243. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93244. var task = new ImageAssetTask(taskName, url);
  93245. this._tasks.push(task);
  93246. return task;
  93247. };
  93248. /**
  93249. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93250. * @param taskName defines the name of the new task
  93251. * @param url defines the url of the file to load
  93252. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93253. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93254. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93255. * @returns a new {BABYLON.TextureAssetTask} object
  93256. */
  93257. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93259. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93260. this._tasks.push(task);
  93261. return task;
  93262. };
  93263. /**
  93264. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93265. * @param taskName defines the name of the new task
  93266. * @param url defines the url of the file to load
  93267. * @param extensions defines the extension to use to load the cube map (can be null)
  93268. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93269. * @param files defines the list of files to load (can be null)
  93270. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93271. */
  93272. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93273. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93274. this._tasks.push(task);
  93275. return task;
  93276. };
  93277. /**
  93278. *
  93279. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93280. * @param taskName defines the name of the new task
  93281. * @param url defines the url of the file to load
  93282. * @param size defines the size you want for the cubemap (can be null)
  93283. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93284. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93285. * @param gammaSpace 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)
  93286. * @param reserved Internal use only
  93287. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93288. */
  93289. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93290. if (noMipmap === void 0) { noMipmap = false; }
  93291. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93292. if (gammaSpace === void 0) { gammaSpace = false; }
  93293. if (reserved === void 0) { reserved = false; }
  93294. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93295. this._tasks.push(task);
  93296. return task;
  93297. };
  93298. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93299. var _this = this;
  93300. this._waitingTasksCount--;
  93301. try {
  93302. if (task.taskState === AssetTaskState.DONE) {
  93303. // Let's remove successfull tasks
  93304. BABYLON.Tools.SetImmediate(function () {
  93305. var index = _this._tasks.indexOf(task);
  93306. if (index > -1) {
  93307. _this._tasks.splice(index, 1);
  93308. }
  93309. });
  93310. }
  93311. if (this.onProgress) {
  93312. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93313. }
  93314. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93315. }
  93316. catch (e) {
  93317. BABYLON.Tools.Error("Error running progress callbacks.");
  93318. console.log(e);
  93319. }
  93320. if (this._waitingTasksCount === 0) {
  93321. try {
  93322. if (this.onFinish) {
  93323. this.onFinish(this._tasks);
  93324. }
  93325. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93326. }
  93327. catch (e) {
  93328. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93329. console.log(e);
  93330. }
  93331. this._isLoading = false;
  93332. this._scene.getEngine().hideLoadingUI();
  93333. }
  93334. };
  93335. AssetsManager.prototype._runTask = function (task) {
  93336. var _this = this;
  93337. var done = function () {
  93338. try {
  93339. if (_this.onTaskSuccess) {
  93340. _this.onTaskSuccess(task);
  93341. }
  93342. _this.onTaskSuccessObservable.notifyObservers(task);
  93343. _this._decreaseWaitingTasksCount(task);
  93344. }
  93345. catch (e) {
  93346. error("Error executing task success callbacks", e);
  93347. }
  93348. };
  93349. var error = function (message, exception) {
  93350. task._setErrorObject(message, exception);
  93351. if (_this.onTaskError) {
  93352. _this.onTaskError(task);
  93353. }
  93354. _this.onTaskErrorObservable.notifyObservers(task);
  93355. _this._decreaseWaitingTasksCount(task);
  93356. };
  93357. task.run(this._scene, done, error);
  93358. };
  93359. /**
  93360. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93361. * @return the current instance of the {BABYLON.AssetsManager}
  93362. */
  93363. AssetsManager.prototype.reset = function () {
  93364. this._isLoading = false;
  93365. this._tasks = new Array();
  93366. return this;
  93367. };
  93368. /**
  93369. * Start the loading process
  93370. * @return the current instance of the {BABYLON.AssetsManager}
  93371. */
  93372. AssetsManager.prototype.load = function () {
  93373. if (this._isLoading) {
  93374. return this;
  93375. }
  93376. this._isLoading = true;
  93377. this._waitingTasksCount = this._tasks.length;
  93378. this._totalTasksCount = this._tasks.length;
  93379. if (this._waitingTasksCount === 0) {
  93380. this._isLoading = false;
  93381. if (this.onFinish) {
  93382. this.onFinish(this._tasks);
  93383. }
  93384. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93385. return this;
  93386. }
  93387. if (this.useDefaultLoadingScreen) {
  93388. this._scene.getEngine().displayLoadingUI();
  93389. }
  93390. for (var index = 0; index < this._tasks.length; index++) {
  93391. var task = this._tasks[index];
  93392. this._runTask(task);
  93393. }
  93394. return this;
  93395. };
  93396. return AssetsManager;
  93397. }());
  93398. BABYLON.AssetsManager = AssetsManager;
  93399. })(BABYLON || (BABYLON = {}));
  93400. //# sourceMappingURL=babylon.assetsManager.js.map
  93401. var BABYLON;
  93402. (function (BABYLON) {
  93403. var serializedGeometries = [];
  93404. var serializeGeometry = function (geometry, serializationGeometries) {
  93405. if (serializedGeometries[geometry.id]) {
  93406. return;
  93407. }
  93408. if (geometry.doNotSerialize) {
  93409. return;
  93410. }
  93411. if (geometry instanceof BABYLON.BoxGeometry) {
  93412. serializationGeometries.boxes.push(geometry.serialize());
  93413. }
  93414. else if (geometry instanceof BABYLON.SphereGeometry) {
  93415. serializationGeometries.spheres.push(geometry.serialize());
  93416. }
  93417. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93418. serializationGeometries.cylinders.push(geometry.serialize());
  93419. }
  93420. else if (geometry instanceof BABYLON.TorusGeometry) {
  93421. serializationGeometries.toruses.push(geometry.serialize());
  93422. }
  93423. else if (geometry instanceof BABYLON.GroundGeometry) {
  93424. serializationGeometries.grounds.push(geometry.serialize());
  93425. }
  93426. else if (geometry instanceof BABYLON.Plane) {
  93427. serializationGeometries.planes.push(geometry.serialize());
  93428. }
  93429. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93430. serializationGeometries.torusKnots.push(geometry.serialize());
  93431. }
  93432. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93433. throw new Error("Unknown primitive type");
  93434. }
  93435. else {
  93436. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93437. }
  93438. serializedGeometries[geometry.id] = true;
  93439. };
  93440. var serializeMesh = function (mesh, serializationScene) {
  93441. var serializationObject = {};
  93442. // Geometry
  93443. var geometry = mesh._geometry;
  93444. if (geometry) {
  93445. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93446. // 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
  93447. serializeGeometry(geometry, serializationScene.geometries);
  93448. }
  93449. }
  93450. // Custom
  93451. if (mesh.serialize) {
  93452. mesh.serialize(serializationObject);
  93453. }
  93454. return serializationObject;
  93455. };
  93456. var finalizeSingleMesh = function (mesh, serializationObject) {
  93457. //only works if the mesh is already loaded
  93458. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93459. //serialize material
  93460. if (mesh.material) {
  93461. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93462. serializationObject.materials = serializationObject.materials || [];
  93463. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93464. serializationObject.materials.push(mesh.material.serialize());
  93465. }
  93466. }
  93467. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93468. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93469. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93470. serializationObject.multiMaterials.push(mesh.material.serialize());
  93471. }
  93472. }
  93473. }
  93474. //serialize geometry
  93475. var geometry = mesh._geometry;
  93476. if (geometry) {
  93477. if (!serializationObject.geometries) {
  93478. serializationObject.geometries = {};
  93479. serializationObject.geometries.boxes = [];
  93480. serializationObject.geometries.spheres = [];
  93481. serializationObject.geometries.cylinders = [];
  93482. serializationObject.geometries.toruses = [];
  93483. serializationObject.geometries.grounds = [];
  93484. serializationObject.geometries.planes = [];
  93485. serializationObject.geometries.torusKnots = [];
  93486. serializationObject.geometries.vertexData = [];
  93487. }
  93488. serializeGeometry(geometry, serializationObject.geometries);
  93489. }
  93490. // Skeletons
  93491. if (mesh.skeleton) {
  93492. serializationObject.skeletons = serializationObject.skeletons || [];
  93493. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93494. }
  93495. //serialize the actual mesh
  93496. serializationObject.meshes = serializationObject.meshes || [];
  93497. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93498. }
  93499. };
  93500. var SceneSerializer = /** @class */ (function () {
  93501. function SceneSerializer() {
  93502. }
  93503. SceneSerializer.ClearCache = function () {
  93504. serializedGeometries = [];
  93505. };
  93506. SceneSerializer.Serialize = function (scene) {
  93507. var serializationObject = {};
  93508. SceneSerializer.ClearCache();
  93509. // Scene
  93510. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93511. serializationObject.autoClear = scene.autoClear;
  93512. serializationObject.clearColor = scene.clearColor.asArray();
  93513. serializationObject.ambientColor = scene.ambientColor.asArray();
  93514. serializationObject.gravity = scene.gravity.asArray();
  93515. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93516. serializationObject.workerCollisions = scene.workerCollisions;
  93517. // Fog
  93518. if (scene.fogMode && scene.fogMode !== 0) {
  93519. serializationObject.fogMode = scene.fogMode;
  93520. serializationObject.fogColor = scene.fogColor.asArray();
  93521. serializationObject.fogStart = scene.fogStart;
  93522. serializationObject.fogEnd = scene.fogEnd;
  93523. serializationObject.fogDensity = scene.fogDensity;
  93524. }
  93525. //Physics
  93526. if (scene.isPhysicsEnabled()) {
  93527. var physicEngine = scene.getPhysicsEngine();
  93528. if (physicEngine) {
  93529. serializationObject.physicsEnabled = true;
  93530. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93531. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93532. }
  93533. }
  93534. // Metadata
  93535. if (scene.metadata) {
  93536. serializationObject.metadata = scene.metadata;
  93537. }
  93538. // Morph targets
  93539. serializationObject.morphTargetManagers = [];
  93540. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93541. var abstractMesh = _a[_i];
  93542. var manager = abstractMesh.morphTargetManager;
  93543. if (manager) {
  93544. serializationObject.morphTargetManagers.push(manager.serialize());
  93545. }
  93546. }
  93547. // Lights
  93548. serializationObject.lights = [];
  93549. var index;
  93550. var light;
  93551. for (index = 0; index < scene.lights.length; index++) {
  93552. light = scene.lights[index];
  93553. if (!light.doNotSerialize) {
  93554. serializationObject.lights.push(light.serialize());
  93555. }
  93556. }
  93557. // Cameras
  93558. serializationObject.cameras = [];
  93559. for (index = 0; index < scene.cameras.length; index++) {
  93560. var camera = scene.cameras[index];
  93561. if (!camera.doNotSerialize) {
  93562. serializationObject.cameras.push(camera.serialize());
  93563. }
  93564. }
  93565. if (scene.activeCamera) {
  93566. serializationObject.activeCameraID = scene.activeCamera.id;
  93567. }
  93568. // Animations
  93569. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93570. // Materials
  93571. serializationObject.materials = [];
  93572. serializationObject.multiMaterials = [];
  93573. var material;
  93574. for (index = 0; index < scene.materials.length; index++) {
  93575. material = scene.materials[index];
  93576. if (!material.doNotSerialize) {
  93577. serializationObject.materials.push(material.serialize());
  93578. }
  93579. }
  93580. // MultiMaterials
  93581. serializationObject.multiMaterials = [];
  93582. for (index = 0; index < scene.multiMaterials.length; index++) {
  93583. var multiMaterial = scene.multiMaterials[index];
  93584. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93585. }
  93586. // Environment texture
  93587. if (scene.environmentTexture) {
  93588. serializationObject.environmentTexture = scene.environmentTexture.name;
  93589. }
  93590. // Skeletons
  93591. serializationObject.skeletons = [];
  93592. for (index = 0; index < scene.skeletons.length; index++) {
  93593. var skeleton = scene.skeletons[index];
  93594. if (!skeleton.doNotSerialize) {
  93595. serializationObject.skeletons.push(skeleton.serialize());
  93596. }
  93597. }
  93598. // Transform nodes
  93599. serializationObject.transformNodes = [];
  93600. for (index = 0; index < scene.transformNodes.length; index++) {
  93601. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93602. }
  93603. // Geometries
  93604. serializationObject.geometries = {};
  93605. serializationObject.geometries.boxes = [];
  93606. serializationObject.geometries.spheres = [];
  93607. serializationObject.geometries.cylinders = [];
  93608. serializationObject.geometries.toruses = [];
  93609. serializationObject.geometries.grounds = [];
  93610. serializationObject.geometries.planes = [];
  93611. serializationObject.geometries.torusKnots = [];
  93612. serializationObject.geometries.vertexData = [];
  93613. serializedGeometries = [];
  93614. var geometries = scene.getGeometries();
  93615. for (index = 0; index < geometries.length; index++) {
  93616. var geometry = geometries[index];
  93617. if (geometry.isReady()) {
  93618. serializeGeometry(geometry, serializationObject.geometries);
  93619. }
  93620. }
  93621. // Meshes
  93622. serializationObject.meshes = [];
  93623. for (index = 0; index < scene.meshes.length; index++) {
  93624. var abstractMesh = scene.meshes[index];
  93625. if (abstractMesh instanceof BABYLON.Mesh) {
  93626. var mesh = abstractMesh;
  93627. if (!mesh.doNotSerialize) {
  93628. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93629. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93630. }
  93631. }
  93632. }
  93633. }
  93634. // Particles Systems
  93635. serializationObject.particleSystems = [];
  93636. for (index = 0; index < scene.particleSystems.length; index++) {
  93637. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93638. }
  93639. // Lens flares
  93640. serializationObject.lensFlareSystems = [];
  93641. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93642. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93643. }
  93644. // Shadows
  93645. serializationObject.shadowGenerators = [];
  93646. for (index = 0; index < scene.lights.length; index++) {
  93647. light = scene.lights[index];
  93648. var shadowGenerator = light.getShadowGenerator();
  93649. if (shadowGenerator) {
  93650. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93651. }
  93652. }
  93653. // Action Manager
  93654. if (scene.actionManager) {
  93655. serializationObject.actions = scene.actionManager.serialize("scene");
  93656. }
  93657. // Audio
  93658. serializationObject.sounds = [];
  93659. for (index = 0; index < scene.soundTracks.length; index++) {
  93660. var soundtrack = scene.soundTracks[index];
  93661. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93662. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93663. }
  93664. }
  93665. // Effect layers
  93666. serializationObject.effectLayers = [];
  93667. for (index = 0; index < scene.effectLayers.length; index++) {
  93668. var layer = scene.effectLayers[index];
  93669. if (layer.serialize) {
  93670. serializationObject.effectLayers.push(layer.serialize());
  93671. }
  93672. }
  93673. return serializationObject;
  93674. };
  93675. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93676. if (withParents === void 0) { withParents = false; }
  93677. if (withChildren === void 0) { withChildren = false; }
  93678. var serializationObject = {};
  93679. SceneSerializer.ClearCache();
  93680. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93681. if (withParents || withChildren) {
  93682. //deliberate for loop! not for each, appended should be processed as well.
  93683. for (var i = 0; i < toSerialize.length; ++i) {
  93684. if (withChildren) {
  93685. toSerialize[i].getDescendants().forEach(function (node) {
  93686. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93687. toSerialize.push(node);
  93688. }
  93689. });
  93690. }
  93691. //make sure the array doesn't contain the object already
  93692. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93693. toSerialize.push(toSerialize[i].parent);
  93694. }
  93695. }
  93696. }
  93697. toSerialize.forEach(function (mesh) {
  93698. finalizeSingleMesh(mesh, serializationObject);
  93699. });
  93700. return serializationObject;
  93701. };
  93702. return SceneSerializer;
  93703. }());
  93704. BABYLON.SceneSerializer = SceneSerializer;
  93705. })(BABYLON || (BABYLON = {}));
  93706. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93707. var BABYLON;
  93708. (function (BABYLON) {
  93709. var ReflectionProbe = /** @class */ (function () {
  93710. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93711. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93712. var _this = this;
  93713. this.name = name;
  93714. this._viewMatrix = BABYLON.Matrix.Identity();
  93715. this._target = BABYLON.Vector3.Zero();
  93716. this._add = BABYLON.Vector3.Zero();
  93717. this._invertYAxis = false;
  93718. this.position = BABYLON.Vector3.Zero();
  93719. this._scene = scene;
  93720. this._scene.reflectionProbes.push(this);
  93721. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93722. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93723. switch (faceIndex) {
  93724. case 0:
  93725. _this._add.copyFromFloats(1, 0, 0);
  93726. break;
  93727. case 1:
  93728. _this._add.copyFromFloats(-1, 0, 0);
  93729. break;
  93730. case 2:
  93731. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93732. break;
  93733. case 3:
  93734. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93735. break;
  93736. case 4:
  93737. _this._add.copyFromFloats(0, 0, 1);
  93738. break;
  93739. case 5:
  93740. _this._add.copyFromFloats(0, 0, -1);
  93741. break;
  93742. }
  93743. if (_this._attachedMesh) {
  93744. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93745. }
  93746. _this.position.addToRef(_this._add, _this._target);
  93747. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93748. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93749. scene._forcedViewPosition = _this.position;
  93750. });
  93751. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93752. scene._forcedViewPosition = null;
  93753. scene.updateTransformMatrix(true);
  93754. });
  93755. if (scene.activeCamera) {
  93756. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93757. }
  93758. }
  93759. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93760. get: function () {
  93761. return this._renderTargetTexture.samples;
  93762. },
  93763. set: function (value) {
  93764. this._renderTargetTexture.samples = value;
  93765. },
  93766. enumerable: true,
  93767. configurable: true
  93768. });
  93769. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93770. get: function () {
  93771. return this._renderTargetTexture.refreshRate;
  93772. },
  93773. set: function (value) {
  93774. this._renderTargetTexture.refreshRate = value;
  93775. },
  93776. enumerable: true,
  93777. configurable: true
  93778. });
  93779. ReflectionProbe.prototype.getScene = function () {
  93780. return this._scene;
  93781. };
  93782. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93783. get: function () {
  93784. return this._renderTargetTexture;
  93785. },
  93786. enumerable: true,
  93787. configurable: true
  93788. });
  93789. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93790. get: function () {
  93791. return this._renderTargetTexture.renderList;
  93792. },
  93793. enumerable: true,
  93794. configurable: true
  93795. });
  93796. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93797. this._attachedMesh = mesh;
  93798. };
  93799. /**
  93800. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93801. *
  93802. * @param renderingGroupId The rendering group id corresponding to its index
  93803. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93804. */
  93805. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93806. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93807. };
  93808. ReflectionProbe.prototype.dispose = function () {
  93809. var index = this._scene.reflectionProbes.indexOf(this);
  93810. if (index !== -1) {
  93811. // Remove from the scene if found
  93812. this._scene.reflectionProbes.splice(index, 1);
  93813. }
  93814. if (this._renderTargetTexture) {
  93815. this._renderTargetTexture.dispose();
  93816. this._renderTargetTexture = null;
  93817. }
  93818. };
  93819. return ReflectionProbe;
  93820. }());
  93821. BABYLON.ReflectionProbe = ReflectionProbe;
  93822. })(BABYLON || (BABYLON = {}));
  93823. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93824. var BABYLON;
  93825. (function (BABYLON) {
  93826. var Layer = /** @class */ (function () {
  93827. function Layer(name, imgUrl, scene, isBackground, color) {
  93828. this.name = name;
  93829. this.scale = new BABYLON.Vector2(1, 1);
  93830. this.offset = new BABYLON.Vector2(0, 0);
  93831. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93832. this.layerMask = 0x0FFFFFFF;
  93833. this._vertexBuffers = {};
  93834. // Events
  93835. /**
  93836. * An event triggered when the layer is disposed.
  93837. */
  93838. this.onDisposeObservable = new BABYLON.Observable();
  93839. /**
  93840. * An event triggered before rendering the scene
  93841. */
  93842. this.onBeforeRenderObservable = new BABYLON.Observable();
  93843. /**
  93844. * An event triggered after rendering the scene
  93845. */
  93846. this.onAfterRenderObservable = new BABYLON.Observable();
  93847. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93848. this.isBackground = isBackground === undefined ? true : isBackground;
  93849. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93850. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93851. this._scene.layers.push(this);
  93852. var engine = this._scene.getEngine();
  93853. // VBO
  93854. var vertices = [];
  93855. vertices.push(1, 1);
  93856. vertices.push(-1, 1);
  93857. vertices.push(-1, -1);
  93858. vertices.push(1, -1);
  93859. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93861. this._createIndexBuffer();
  93862. // Effects
  93863. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93864. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93865. }
  93866. Object.defineProperty(Layer.prototype, "onDispose", {
  93867. set: function (callback) {
  93868. if (this._onDisposeObserver) {
  93869. this.onDisposeObservable.remove(this._onDisposeObserver);
  93870. }
  93871. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93872. },
  93873. enumerable: true,
  93874. configurable: true
  93875. });
  93876. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93877. set: function (callback) {
  93878. if (this._onBeforeRenderObserver) {
  93879. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93880. }
  93881. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93882. },
  93883. enumerable: true,
  93884. configurable: true
  93885. });
  93886. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93887. set: function (callback) {
  93888. if (this._onAfterRenderObserver) {
  93889. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93890. }
  93891. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93892. },
  93893. enumerable: true,
  93894. configurable: true
  93895. });
  93896. Layer.prototype._createIndexBuffer = function () {
  93897. var engine = this._scene.getEngine();
  93898. // Indices
  93899. var indices = [];
  93900. indices.push(0);
  93901. indices.push(1);
  93902. indices.push(2);
  93903. indices.push(0);
  93904. indices.push(2);
  93905. indices.push(3);
  93906. this._indexBuffer = engine.createIndexBuffer(indices);
  93907. };
  93908. Layer.prototype._rebuild = function () {
  93909. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93910. if (vb) {
  93911. vb._rebuild();
  93912. }
  93913. this._createIndexBuffer();
  93914. };
  93915. Layer.prototype.render = function () {
  93916. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93917. // Check
  93918. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93919. return;
  93920. var engine = this._scene.getEngine();
  93921. this.onBeforeRenderObservable.notifyObservers(this);
  93922. // Render
  93923. engine.enableEffect(currentEffect);
  93924. engine.setState(false);
  93925. // Texture
  93926. currentEffect.setTexture("textureSampler", this.texture);
  93927. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93928. // Color
  93929. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93930. // Scale / offset
  93931. currentEffect.setVector2("offset", this.offset);
  93932. currentEffect.setVector2("scale", this.scale);
  93933. // VBOs
  93934. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93935. // Draw order
  93936. if (!this.alphaTest) {
  93937. engine.setAlphaMode(this.alphaBlendingMode);
  93938. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93939. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93940. }
  93941. else {
  93942. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93943. }
  93944. this.onAfterRenderObservable.notifyObservers(this);
  93945. };
  93946. Layer.prototype.dispose = function () {
  93947. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93948. if (vertexBuffer) {
  93949. vertexBuffer.dispose();
  93950. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93951. }
  93952. if (this._indexBuffer) {
  93953. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93954. this._indexBuffer = null;
  93955. }
  93956. if (this.texture) {
  93957. this.texture.dispose();
  93958. this.texture = null;
  93959. }
  93960. // Remove from scene
  93961. var index = this._scene.layers.indexOf(this);
  93962. this._scene.layers.splice(index, 1);
  93963. // Callback
  93964. this.onDisposeObservable.notifyObservers(this);
  93965. this.onDisposeObservable.clear();
  93966. this.onAfterRenderObservable.clear();
  93967. this.onBeforeRenderObservable.clear();
  93968. };
  93969. return Layer;
  93970. }());
  93971. BABYLON.Layer = Layer;
  93972. })(BABYLON || (BABYLON = {}));
  93973. //# sourceMappingURL=babylon.layer.js.map
  93974. var BABYLON;
  93975. (function (BABYLON) {
  93976. var TextureTools = /** @class */ (function () {
  93977. function TextureTools() {
  93978. }
  93979. /**
  93980. * Uses the GPU to create a copy texture rescaled at a given size
  93981. * @param texture Texture to copy from
  93982. * @param width Desired width
  93983. * @param height Desired height
  93984. * @return Generated texture
  93985. */
  93986. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93987. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93988. var scene = texture.getScene();
  93989. var engine = scene.getEngine();
  93990. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93991. rtt.wrapU = texture.wrapU;
  93992. rtt.wrapV = texture.wrapV;
  93993. rtt.uOffset = texture.uOffset;
  93994. rtt.vOffset = texture.vOffset;
  93995. rtt.uScale = texture.uScale;
  93996. rtt.vScale = texture.vScale;
  93997. rtt.uAng = texture.uAng;
  93998. rtt.vAng = texture.vAng;
  93999. rtt.wAng = texture.wAng;
  94000. rtt.coordinatesIndex = texture.coordinatesIndex;
  94001. rtt.level = texture.level;
  94002. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94003. rtt._texture.isReady = false;
  94004. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94005. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94006. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94007. passPostProcess.getEffect().executeWhenCompiled(function () {
  94008. passPostProcess.onApply = function (effect) {
  94009. effect.setTexture("textureSampler", texture);
  94010. };
  94011. var internalTexture = rtt.getInternalTexture();
  94012. if (internalTexture) {
  94013. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94014. engine.unBindFramebuffer(internalTexture);
  94015. rtt.disposeFramebufferObjects();
  94016. passPostProcess.dispose();
  94017. internalTexture.isReady = true;
  94018. }
  94019. });
  94020. return rtt;
  94021. };
  94022. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94023. if (!scene._environmentBRDFTexture) {
  94024. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94025. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94026. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94027. scene._environmentBRDFTexture = texture;
  94028. }
  94029. return scene._environmentBRDFTexture;
  94030. };
  94031. 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=";
  94032. return TextureTools;
  94033. }());
  94034. BABYLON.TextureTools = TextureTools;
  94035. })(BABYLON || (BABYLON = {}));
  94036. //# sourceMappingURL=babylon.textureTools.js.map
  94037. var BABYLON;
  94038. (function (BABYLON) {
  94039. var FramingBehavior = /** @class */ (function () {
  94040. function FramingBehavior() {
  94041. this._mode = FramingBehavior.FitFrustumSidesMode;
  94042. this._radiusScale = 1.0;
  94043. this._positionScale = 0.5;
  94044. this._defaultElevation = 0.3;
  94045. this._elevationReturnTime = 1500;
  94046. this._elevationReturnWaitTime = 1000;
  94047. this._zoomStopsAnimation = false;
  94048. this._framingTime = 1500;
  94049. this._isPointerDown = false;
  94050. this._lastInteractionTime = -Infinity;
  94051. // Framing control
  94052. this._animatables = new Array();
  94053. this._betaIsAnimating = false;
  94054. }
  94055. Object.defineProperty(FramingBehavior.prototype, "name", {
  94056. get: function () {
  94057. return "Framing";
  94058. },
  94059. enumerable: true,
  94060. configurable: true
  94061. });
  94062. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94063. /**
  94064. * Gets current mode used by the behavior.
  94065. */
  94066. get: function () {
  94067. return this._mode;
  94068. },
  94069. /**
  94070. * Sets the current mode used by the behavior
  94071. */
  94072. set: function (mode) {
  94073. this._mode = mode;
  94074. },
  94075. enumerable: true,
  94076. configurable: true
  94077. });
  94078. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94079. /**
  94080. * Gets the scale applied to the radius
  94081. */
  94082. get: function () {
  94083. return this._radiusScale;
  94084. },
  94085. /**
  94086. * Sets the scale applied to the radius (1 by default)
  94087. */
  94088. set: function (radius) {
  94089. this._radiusScale = radius;
  94090. },
  94091. enumerable: true,
  94092. configurable: true
  94093. });
  94094. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94095. /**
  94096. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94097. */
  94098. get: function () {
  94099. return this._positionScale;
  94100. },
  94101. /**
  94102. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94103. */
  94104. set: function (scale) {
  94105. this._positionScale = scale;
  94106. },
  94107. enumerable: true,
  94108. configurable: true
  94109. });
  94110. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94111. /**
  94112. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94113. * behaviour is triggered, in radians.
  94114. */
  94115. get: function () {
  94116. return this._defaultElevation;
  94117. },
  94118. /**
  94119. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94120. * behaviour is triggered, in radians.
  94121. */
  94122. set: function (elevation) {
  94123. this._defaultElevation = elevation;
  94124. },
  94125. enumerable: true,
  94126. configurable: true
  94127. });
  94128. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94129. /**
  94130. * Gets the time (in milliseconds) taken to return to the default beta position.
  94131. * Negative value indicates camera should not return to default.
  94132. */
  94133. get: function () {
  94134. return this._elevationReturnTime;
  94135. },
  94136. /**
  94137. * Sets the time (in milliseconds) taken to return to the default beta position.
  94138. * Negative value indicates camera should not return to default.
  94139. */
  94140. set: function (speed) {
  94141. this._elevationReturnTime = speed;
  94142. },
  94143. enumerable: true,
  94144. configurable: true
  94145. });
  94146. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94147. /**
  94148. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94149. */
  94150. get: function () {
  94151. return this._elevationReturnWaitTime;
  94152. },
  94153. /**
  94154. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94155. */
  94156. set: function (time) {
  94157. this._elevationReturnWaitTime = time;
  94158. },
  94159. enumerable: true,
  94160. configurable: true
  94161. });
  94162. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94163. /**
  94164. * Gets the flag that indicates if user zooming should stop animation.
  94165. */
  94166. get: function () {
  94167. return this._zoomStopsAnimation;
  94168. },
  94169. /**
  94170. * Sets the flag that indicates if user zooming should stop animation.
  94171. */
  94172. set: function (flag) {
  94173. this._zoomStopsAnimation = flag;
  94174. },
  94175. enumerable: true,
  94176. configurable: true
  94177. });
  94178. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94179. /**
  94180. * Gets the transition time when framing the mesh, in milliseconds
  94181. */
  94182. get: function () {
  94183. return this._framingTime;
  94184. },
  94185. /**
  94186. * Sets the transition time when framing the mesh, in milliseconds
  94187. */
  94188. set: function (time) {
  94189. this._framingTime = time;
  94190. },
  94191. enumerable: true,
  94192. configurable: true
  94193. });
  94194. FramingBehavior.prototype.init = function () {
  94195. // Do notihng
  94196. };
  94197. FramingBehavior.prototype.attach = function (camera) {
  94198. var _this = this;
  94199. this._attachedCamera = camera;
  94200. var scene = this._attachedCamera.getScene();
  94201. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94202. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94203. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94204. _this._isPointerDown = true;
  94205. return;
  94206. }
  94207. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94208. _this._isPointerDown = false;
  94209. }
  94210. });
  94211. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94212. if (mesh) {
  94213. _this.zoomOnMesh(mesh);
  94214. }
  94215. });
  94216. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94217. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94218. _this._applyUserInteraction();
  94219. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94220. // back to the default position after a given timeout
  94221. _this._maintainCameraAboveGround();
  94222. });
  94223. };
  94224. FramingBehavior.prototype.detach = function () {
  94225. if (!this._attachedCamera) {
  94226. return;
  94227. }
  94228. var scene = this._attachedCamera.getScene();
  94229. if (this._onPrePointerObservableObserver) {
  94230. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94231. }
  94232. if (this._onAfterCheckInputsObserver) {
  94233. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94234. }
  94235. if (this._onMeshTargetChangedObserver) {
  94236. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94237. }
  94238. this._attachedCamera = null;
  94239. };
  94240. /**
  94241. * Targets the given mesh and updates zoom level accordingly.
  94242. * @param mesh The mesh to target.
  94243. * @param radius Optional. If a cached radius position already exists, overrides default.
  94244. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94245. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94246. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94247. */
  94248. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94249. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94250. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94251. mesh.computeWorldMatrix(true);
  94252. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94253. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94254. };
  94255. /**
  94256. * Targets the given mesh with its children and updates zoom level accordingly.
  94257. * @param mesh The mesh to target.
  94258. * @param radius Optional. If a cached radius position already exists, overrides default.
  94259. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94260. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94261. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94262. */
  94263. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94264. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94265. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94266. mesh.computeWorldMatrix(true);
  94267. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94268. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94269. };
  94270. /**
  94271. * Targets the given meshes with their children and updates zoom level accordingly.
  94272. * @param meshes The mesh to target.
  94273. * @param radius Optional. If a cached radius position already exists, overrides default.
  94274. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94275. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94276. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94277. */
  94278. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94279. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94280. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94281. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94282. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94283. for (var i = 0; i < meshes.length; i++) {
  94284. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94285. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94286. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94287. }
  94288. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94289. };
  94290. /**
  94291. * Targets the given mesh and updates zoom level accordingly.
  94292. * @param mesh The mesh to target.
  94293. * @param radius Optional. If a cached radius position already exists, overrides default.
  94294. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94295. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94296. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94297. */
  94298. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94299. var _this = this;
  94300. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94301. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94302. var zoomTarget;
  94303. if (!this._attachedCamera) {
  94304. return;
  94305. }
  94306. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94307. var bottom = minimumWorld.y;
  94308. var top = maximumWorld.y;
  94309. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94310. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94311. if (focusOnOriginXZ) {
  94312. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94313. }
  94314. else {
  94315. var centerWorld = minimumWorld.add(radiusWorld);
  94316. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94317. }
  94318. if (!this._vectorTransition) {
  94319. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94320. }
  94321. this._betaIsAnimating = true;
  94322. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94323. if (animatable) {
  94324. this._animatables.push(animatable);
  94325. }
  94326. // sets the radius and lower radius bounds
  94327. // Small delta ensures camera is not always at lower zoom limit.
  94328. var radius = 0;
  94329. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94330. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94331. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94332. radius = position;
  94333. }
  94334. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94335. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94336. if (this._attachedCamera.lowerRadiusLimit === null) {
  94337. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94338. }
  94339. }
  94340. // Set sensibilities
  94341. var extend = maximumWorld.subtract(minimumWorld).length();
  94342. this._attachedCamera.panningSensibility = 5000 / extend;
  94343. this._attachedCamera.wheelPrecision = 100 / radius;
  94344. // transition to new radius
  94345. if (!this._radiusTransition) {
  94346. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94347. }
  94348. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94349. _this.stopAllAnimations();
  94350. if (onAnimationEnd) {
  94351. onAnimationEnd();
  94352. }
  94353. if (_this._attachedCamera) {
  94354. _this._attachedCamera.storeState();
  94355. }
  94356. });
  94357. if (animatable) {
  94358. this._animatables.push(animatable);
  94359. }
  94360. };
  94361. /**
  94362. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94363. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94364. * frustum width.
  94365. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94366. * to fully enclose the mesh in the viewing frustum.
  94367. */
  94368. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94369. var size = maximumWorld.subtract(minimumWorld);
  94370. var boxVectorGlobalDiagonal = size.length();
  94371. var frustumSlope = this._getFrustumSlope();
  94372. // Formula for setting distance
  94373. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94374. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94375. // Horizon distance
  94376. var radius = radiusWithoutFraming * this._radiusScale;
  94377. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94378. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94379. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94380. var camera = this._attachedCamera;
  94381. if (!camera) {
  94382. return 0;
  94383. }
  94384. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94385. // Don't exceed the requested limit
  94386. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94387. }
  94388. // Don't exceed the upper radius limit
  94389. if (camera.upperRadiusLimit) {
  94390. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94391. }
  94392. return distance;
  94393. };
  94394. /**
  94395. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94396. * is automatically returned to its default position (expected to be above ground plane).
  94397. */
  94398. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94399. var _this = this;
  94400. if (this._elevationReturnTime < 0) {
  94401. return;
  94402. }
  94403. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94404. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94405. var limitBeta = Math.PI * 0.5;
  94406. // Bring the camera back up if below the ground plane
  94407. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94408. this._betaIsAnimating = true;
  94409. //Transition to new position
  94410. this.stopAllAnimations();
  94411. if (!this._betaTransition) {
  94412. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94413. }
  94414. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94415. _this._clearAnimationLocks();
  94416. _this.stopAllAnimations();
  94417. });
  94418. if (animatabe) {
  94419. this._animatables.push(animatabe);
  94420. }
  94421. }
  94422. };
  94423. /**
  94424. * Returns the frustum slope based on the canvas ratio and camera FOV
  94425. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94426. */
  94427. FramingBehavior.prototype._getFrustumSlope = function () {
  94428. // Calculate the viewport ratio
  94429. // Aspect Ratio is Height/Width.
  94430. var camera = this._attachedCamera;
  94431. if (!camera) {
  94432. return BABYLON.Vector2.Zero();
  94433. }
  94434. var engine = camera.getScene().getEngine();
  94435. var aspectRatio = engine.getAspectRatio(camera);
  94436. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94437. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94438. var frustumSlopeY = Math.tan(camera.fov / 2);
  94439. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94440. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94441. // along the forward vector.
  94442. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94443. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94444. };
  94445. /**
  94446. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94447. */
  94448. FramingBehavior.prototype._clearAnimationLocks = function () {
  94449. this._betaIsAnimating = false;
  94450. };
  94451. /**
  94452. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94453. */
  94454. FramingBehavior.prototype._applyUserInteraction = function () {
  94455. if (this.isUserIsMoving) {
  94456. this._lastInteractionTime = BABYLON.Tools.Now;
  94457. this.stopAllAnimations();
  94458. this._clearAnimationLocks();
  94459. }
  94460. };
  94461. /**
  94462. * Stops and removes all animations that have been applied to the camera
  94463. */
  94464. FramingBehavior.prototype.stopAllAnimations = function () {
  94465. if (this._attachedCamera) {
  94466. this._attachedCamera.animations = [];
  94467. }
  94468. while (this._animatables.length) {
  94469. if (this._animatables[0]) {
  94470. this._animatables[0].onAnimationEnd = null;
  94471. this._animatables[0].stop();
  94472. }
  94473. this._animatables.shift();
  94474. }
  94475. };
  94476. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94477. /**
  94478. * Gets a value indicating if the user is moving the camera
  94479. */
  94480. get: function () {
  94481. if (!this._attachedCamera) {
  94482. return false;
  94483. }
  94484. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94485. this._attachedCamera.inertialBetaOffset !== 0 ||
  94486. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94487. this._attachedCamera.inertialPanningX !== 0 ||
  94488. this._attachedCamera.inertialPanningY !== 0 ||
  94489. this._isPointerDown;
  94490. },
  94491. enumerable: true,
  94492. configurable: true
  94493. });
  94494. /**
  94495. * The easing function used by animations
  94496. */
  94497. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94498. /**
  94499. * The easing mode used by animations
  94500. */
  94501. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94502. // Statics
  94503. /**
  94504. * The camera can move all the way towards the mesh.
  94505. */
  94506. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94507. /**
  94508. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94509. */
  94510. FramingBehavior.FitFrustumSidesMode = 1;
  94511. return FramingBehavior;
  94512. }());
  94513. BABYLON.FramingBehavior = FramingBehavior;
  94514. })(BABYLON || (BABYLON = {}));
  94515. //# sourceMappingURL=babylon.framingBehavior.js.map
  94516. var BABYLON;
  94517. (function (BABYLON) {
  94518. /**
  94519. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94520. */
  94521. var BouncingBehavior = /** @class */ (function () {
  94522. function BouncingBehavior() {
  94523. /**
  94524. * The duration of the animation, in milliseconds
  94525. */
  94526. this.transitionDuration = 450;
  94527. /**
  94528. * Length of the distance animated by the transition when lower radius is reached
  94529. */
  94530. this.lowerRadiusTransitionRange = 2;
  94531. /**
  94532. * Length of the distance animated by the transition when upper radius is reached
  94533. */
  94534. this.upperRadiusTransitionRange = -2;
  94535. this._autoTransitionRange = false;
  94536. // Animations
  94537. this._radiusIsAnimating = false;
  94538. this._radiusBounceTransition = null;
  94539. this._animatables = new Array();
  94540. }
  94541. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94542. get: function () {
  94543. return "Bouncing";
  94544. },
  94545. enumerable: true,
  94546. configurable: true
  94547. });
  94548. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94549. /**
  94550. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94551. */
  94552. get: function () {
  94553. return this._autoTransitionRange;
  94554. },
  94555. /**
  94556. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94557. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94558. */
  94559. set: function (value) {
  94560. var _this = this;
  94561. if (this._autoTransitionRange === value) {
  94562. return;
  94563. }
  94564. this._autoTransitionRange = value;
  94565. var camera = this._attachedCamera;
  94566. if (!camera) {
  94567. return;
  94568. }
  94569. if (value) {
  94570. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94571. if (!mesh) {
  94572. return;
  94573. }
  94574. mesh.computeWorldMatrix(true);
  94575. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94576. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94577. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94578. });
  94579. }
  94580. else if (this._onMeshTargetChangedObserver) {
  94581. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94582. }
  94583. },
  94584. enumerable: true,
  94585. configurable: true
  94586. });
  94587. BouncingBehavior.prototype.init = function () {
  94588. // Do notihng
  94589. };
  94590. BouncingBehavior.prototype.attach = function (camera) {
  94591. var _this = this;
  94592. this._attachedCamera = camera;
  94593. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94594. if (!_this._attachedCamera) {
  94595. return;
  94596. }
  94597. // Add the bounce animation to the lower radius limit
  94598. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94599. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94600. }
  94601. // Add the bounce animation to the upper radius limit
  94602. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94603. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94604. }
  94605. });
  94606. };
  94607. BouncingBehavior.prototype.detach = function () {
  94608. if (!this._attachedCamera) {
  94609. return;
  94610. }
  94611. if (this._onAfterCheckInputsObserver) {
  94612. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94613. }
  94614. if (this._onMeshTargetChangedObserver) {
  94615. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94616. }
  94617. this._attachedCamera = null;
  94618. };
  94619. /**
  94620. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94621. * @param radiusLimit The limit to check against.
  94622. * @return Bool to indicate if at limit.
  94623. */
  94624. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94625. if (!this._attachedCamera) {
  94626. return false;
  94627. }
  94628. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94629. return true;
  94630. }
  94631. return false;
  94632. };
  94633. /**
  94634. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94635. * @param radiusDelta The delta by which to animate to. Can be negative.
  94636. */
  94637. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94638. var _this = this;
  94639. if (!this._attachedCamera) {
  94640. return;
  94641. }
  94642. if (!this._radiusBounceTransition) {
  94643. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94644. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94645. }
  94646. // Prevent zoom until bounce has completed
  94647. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94648. this._attachedCamera.wheelPrecision = Infinity;
  94649. this._attachedCamera.inertialRadiusOffset = 0;
  94650. // Animate to the radius limit
  94651. this.stopAllAnimations();
  94652. this._radiusIsAnimating = true;
  94653. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94654. if (animatable) {
  94655. this._animatables.push(animatable);
  94656. }
  94657. };
  94658. /**
  94659. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94660. */
  94661. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94662. this._radiusIsAnimating = false;
  94663. if (this._attachedCamera) {
  94664. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94665. }
  94666. };
  94667. /**
  94668. * Stops and removes all animations that have been applied to the camera
  94669. */
  94670. BouncingBehavior.prototype.stopAllAnimations = function () {
  94671. if (this._attachedCamera) {
  94672. this._attachedCamera.animations = [];
  94673. }
  94674. while (this._animatables.length) {
  94675. this._animatables[0].onAnimationEnd = null;
  94676. this._animatables[0].stop();
  94677. this._animatables.shift();
  94678. }
  94679. };
  94680. /**
  94681. * The easing function used by animations
  94682. */
  94683. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94684. /**
  94685. * The easing mode used by animations
  94686. */
  94687. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94688. return BouncingBehavior;
  94689. }());
  94690. BABYLON.BouncingBehavior = BouncingBehavior;
  94691. })(BABYLON || (BABYLON = {}));
  94692. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94693. var BABYLON;
  94694. (function (BABYLON) {
  94695. var AutoRotationBehavior = /** @class */ (function () {
  94696. function AutoRotationBehavior() {
  94697. this._zoomStopsAnimation = false;
  94698. this._idleRotationSpeed = 0.05;
  94699. this._idleRotationWaitTime = 2000;
  94700. this._idleRotationSpinupTime = 2000;
  94701. this._isPointerDown = false;
  94702. this._lastFrameTime = null;
  94703. this._lastInteractionTime = -Infinity;
  94704. this._cameraRotationSpeed = 0;
  94705. this._lastFrameRadius = 0;
  94706. }
  94707. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94708. get: function () {
  94709. return "AutoRotation";
  94710. },
  94711. enumerable: true,
  94712. configurable: true
  94713. });
  94714. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94715. /**
  94716. * Gets the flag that indicates if user zooming should stop animation.
  94717. */
  94718. get: function () {
  94719. return this._zoomStopsAnimation;
  94720. },
  94721. /**
  94722. * Sets the flag that indicates if user zooming should stop animation.
  94723. */
  94724. set: function (flag) {
  94725. this._zoomStopsAnimation = flag;
  94726. },
  94727. enumerable: true,
  94728. configurable: true
  94729. });
  94730. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94731. /**
  94732. * Gets the default speed at which the camera rotates around the model.
  94733. */
  94734. get: function () {
  94735. return this._idleRotationSpeed;
  94736. },
  94737. /**
  94738. * Sets the default speed at which the camera rotates around the model.
  94739. */
  94740. set: function (speed) {
  94741. this._idleRotationSpeed = speed;
  94742. },
  94743. enumerable: true,
  94744. configurable: true
  94745. });
  94746. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94747. /**
  94748. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94749. */
  94750. get: function () {
  94751. return this._idleRotationWaitTime;
  94752. },
  94753. /**
  94754. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94755. */
  94756. set: function (time) {
  94757. this._idleRotationWaitTime = time;
  94758. },
  94759. enumerable: true,
  94760. configurable: true
  94761. });
  94762. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94763. /**
  94764. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94765. */
  94766. get: function () {
  94767. return this._idleRotationSpinupTime;
  94768. },
  94769. /**
  94770. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94771. */
  94772. set: function (time) {
  94773. this._idleRotationSpinupTime = time;
  94774. },
  94775. enumerable: true,
  94776. configurable: true
  94777. });
  94778. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94779. /**
  94780. * Gets a value indicating if the camera is currently rotating because of this behavior
  94781. */
  94782. get: function () {
  94783. return Math.abs(this._cameraRotationSpeed) > 0;
  94784. },
  94785. enumerable: true,
  94786. configurable: true
  94787. });
  94788. AutoRotationBehavior.prototype.init = function () {
  94789. // Do notihng
  94790. };
  94791. AutoRotationBehavior.prototype.attach = function (camera) {
  94792. var _this = this;
  94793. this._attachedCamera = camera;
  94794. var scene = this._attachedCamera.getScene();
  94795. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94796. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94797. _this._isPointerDown = true;
  94798. return;
  94799. }
  94800. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94801. _this._isPointerDown = false;
  94802. }
  94803. });
  94804. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94805. var now = BABYLON.Tools.Now;
  94806. var dt = 0;
  94807. if (_this._lastFrameTime != null) {
  94808. dt = now - _this._lastFrameTime;
  94809. }
  94810. _this._lastFrameTime = now;
  94811. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94812. _this._applyUserInteraction();
  94813. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94814. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94815. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94816. // Step camera rotation by rotation speed
  94817. if (_this._attachedCamera) {
  94818. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94819. }
  94820. });
  94821. };
  94822. AutoRotationBehavior.prototype.detach = function () {
  94823. if (!this._attachedCamera) {
  94824. return;
  94825. }
  94826. var scene = this._attachedCamera.getScene();
  94827. if (this._onPrePointerObservableObserver) {
  94828. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94829. }
  94830. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94831. this._attachedCamera = null;
  94832. };
  94833. /**
  94834. * Returns true if user is scrolling.
  94835. * @return true if user is scrolling.
  94836. */
  94837. AutoRotationBehavior.prototype._userIsZooming = function () {
  94838. if (!this._attachedCamera) {
  94839. return false;
  94840. }
  94841. return this._attachedCamera.inertialRadiusOffset !== 0;
  94842. };
  94843. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94844. if (!this._attachedCamera) {
  94845. return false;
  94846. }
  94847. var zoomHasHitLimit = false;
  94848. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94849. zoomHasHitLimit = true;
  94850. }
  94851. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94852. this._lastFrameRadius = this._attachedCamera.radius;
  94853. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94854. };
  94855. /**
  94856. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94857. */
  94858. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94859. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94860. this._lastInteractionTime = BABYLON.Tools.Now;
  94861. }
  94862. };
  94863. // Tools
  94864. AutoRotationBehavior.prototype._userIsMoving = function () {
  94865. if (!this._attachedCamera) {
  94866. return false;
  94867. }
  94868. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94869. this._attachedCamera.inertialBetaOffset !== 0 ||
  94870. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94871. this._attachedCamera.inertialPanningX !== 0 ||
  94872. this._attachedCamera.inertialPanningY !== 0 ||
  94873. this._isPointerDown;
  94874. };
  94875. return AutoRotationBehavior;
  94876. }());
  94877. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94878. })(BABYLON || (BABYLON = {}));
  94879. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94880. var BABYLON;
  94881. (function (BABYLON) {
  94882. var NullEngineOptions = /** @class */ (function () {
  94883. function NullEngineOptions() {
  94884. this.renderWidth = 512;
  94885. this.renderHeight = 256;
  94886. this.textureSize = 512;
  94887. this.deterministicLockstep = false;
  94888. this.lockstepMaxSteps = 4;
  94889. }
  94890. return NullEngineOptions;
  94891. }());
  94892. BABYLON.NullEngineOptions = NullEngineOptions;
  94893. /**
  94894. * The null engine class provides support for headless version of babylon.js.
  94895. * This can be used in server side scenario or for testing purposes
  94896. */
  94897. var NullEngine = /** @class */ (function (_super) {
  94898. __extends(NullEngine, _super);
  94899. function NullEngine(options) {
  94900. if (options === void 0) { options = new NullEngineOptions(); }
  94901. var _this = _super.call(this, null) || this;
  94902. if (options.deterministicLockstep === undefined) {
  94903. options.deterministicLockstep = false;
  94904. }
  94905. if (options.lockstepMaxSteps === undefined) {
  94906. options.lockstepMaxSteps = 4;
  94907. }
  94908. _this._options = options;
  94909. // Init caps
  94910. // We consider we are on a webgl1 capable device
  94911. _this._caps = new BABYLON.EngineCapabilities();
  94912. _this._caps.maxTexturesImageUnits = 16;
  94913. _this._caps.maxVertexTextureImageUnits = 16;
  94914. _this._caps.maxTextureSize = 512;
  94915. _this._caps.maxCubemapTextureSize = 512;
  94916. _this._caps.maxRenderTextureSize = 512;
  94917. _this._caps.maxVertexAttribs = 16;
  94918. _this._caps.maxVaryingVectors = 16;
  94919. _this._caps.maxFragmentUniformVectors = 16;
  94920. _this._caps.maxVertexUniformVectors = 16;
  94921. // Extensions
  94922. _this._caps.standardDerivatives = false;
  94923. _this._caps.astc = null;
  94924. _this._caps.s3tc = null;
  94925. _this._caps.pvrtc = null;
  94926. _this._caps.etc1 = null;
  94927. _this._caps.etc2 = null;
  94928. _this._caps.textureAnisotropicFilterExtension = null;
  94929. _this._caps.maxAnisotropy = 0;
  94930. _this._caps.uintIndices = false;
  94931. _this._caps.fragmentDepthSupported = false;
  94932. _this._caps.highPrecisionShaderSupported = true;
  94933. _this._caps.colorBufferFloat = false;
  94934. _this._caps.textureFloat = false;
  94935. _this._caps.textureFloatLinearFiltering = false;
  94936. _this._caps.textureFloatRender = false;
  94937. _this._caps.textureHalfFloat = false;
  94938. _this._caps.textureHalfFloatLinearFiltering = false;
  94939. _this._caps.textureHalfFloatRender = false;
  94940. _this._caps.textureLOD = false;
  94941. _this._caps.drawBuffersExtension = false;
  94942. _this._caps.depthTextureExtension = false;
  94943. _this._caps.vertexArrayObject = false;
  94944. _this._caps.instancedArrays = false;
  94945. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94946. // Wrappers
  94947. if (typeof URL === "undefined") {
  94948. URL = {
  94949. createObjectURL: function () { },
  94950. revokeObjectURL: function () { }
  94951. };
  94952. }
  94953. if (typeof Blob === "undefined") {
  94954. Blob = function () { };
  94955. }
  94956. return _this;
  94957. }
  94958. NullEngine.prototype.isDeterministicLockStep = function () {
  94959. return this._options.deterministicLockstep;
  94960. };
  94961. NullEngine.prototype.getLockstepMaxSteps = function () {
  94962. return this._options.lockstepMaxSteps;
  94963. };
  94964. NullEngine.prototype.getHardwareScalingLevel = function () {
  94965. return 1.0;
  94966. };
  94967. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94968. return {
  94969. capacity: 0,
  94970. references: 1,
  94971. is32Bits: false
  94972. };
  94973. };
  94974. NullEngine.prototype.createIndexBuffer = function (indices) {
  94975. return {
  94976. capacity: 0,
  94977. references: 1,
  94978. is32Bits: false
  94979. };
  94980. };
  94981. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94982. if (stencil === void 0) { stencil = false; }
  94983. };
  94984. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94985. if (useScreen === void 0) { useScreen = false; }
  94986. if (!useScreen && this._currentRenderTarget) {
  94987. return this._currentRenderTarget.width;
  94988. }
  94989. return this._options.renderWidth;
  94990. };
  94991. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94992. if (useScreen === void 0) { useScreen = false; }
  94993. if (!useScreen && this._currentRenderTarget) {
  94994. return this._currentRenderTarget.height;
  94995. }
  94996. return this._options.renderHeight;
  94997. };
  94998. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94999. this._cachedViewport = viewport;
  95000. };
  95001. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95002. return {
  95003. transformFeedback: null,
  95004. __SPECTOR_rebuildProgram: null
  95005. };
  95006. };
  95007. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95008. return [];
  95009. };
  95010. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95011. return [];
  95012. };
  95013. NullEngine.prototype.bindSamplers = function (effect) {
  95014. this._currentEffect = null;
  95015. };
  95016. NullEngine.prototype.enableEffect = function (effect) {
  95017. this._currentEffect = effect;
  95018. if (effect.onBind) {
  95019. effect.onBind(effect);
  95020. }
  95021. effect.onBindObservable.notifyObservers(effect);
  95022. };
  95023. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95024. if (zOffset === void 0) { zOffset = 0; }
  95025. if (reverseSide === void 0) { reverseSide = false; }
  95026. };
  95027. NullEngine.prototype.setIntArray = function (uniform, array) {
  95028. };
  95029. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95030. };
  95031. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95032. };
  95033. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95034. };
  95035. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95036. };
  95037. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95038. };
  95039. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95040. };
  95041. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95042. };
  95043. NullEngine.prototype.setArray = function (uniform, array) {
  95044. };
  95045. NullEngine.prototype.setArray2 = function (uniform, array) {
  95046. };
  95047. NullEngine.prototype.setArray3 = function (uniform, array) {
  95048. };
  95049. NullEngine.prototype.setArray4 = function (uniform, array) {
  95050. };
  95051. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95052. };
  95053. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95054. };
  95055. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95056. };
  95057. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95058. };
  95059. NullEngine.prototype.setFloat = function (uniform, value) {
  95060. };
  95061. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95062. };
  95063. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95064. };
  95065. NullEngine.prototype.setBool = function (uniform, bool) {
  95066. };
  95067. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95068. };
  95069. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95070. };
  95071. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95072. };
  95073. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95074. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95075. if (this._alphaMode === mode) {
  95076. return;
  95077. }
  95078. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95079. if (!noDepthWriteChange) {
  95080. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95081. }
  95082. this._alphaMode = mode;
  95083. };
  95084. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95085. };
  95086. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95087. if (this.preventCacheWipeBetweenFrames) {
  95088. return;
  95089. }
  95090. this.resetTextureCache();
  95091. this._currentEffect = null;
  95092. if (bruteForce) {
  95093. this._currentProgram = null;
  95094. this._stencilState.reset();
  95095. this._depthCullingState.reset();
  95096. this._alphaState.reset();
  95097. }
  95098. this._cachedVertexBuffers = null;
  95099. this._cachedIndexBuffer = null;
  95100. this._cachedEffectForVertexBuffers = null;
  95101. };
  95102. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95103. };
  95104. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95105. };
  95106. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95107. };
  95108. NullEngine.prototype._createTexture = function () {
  95109. return {};
  95110. };
  95111. NullEngine.prototype._releaseTexture = function (texture) {
  95112. };
  95113. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95115. if (onLoad === void 0) { onLoad = null; }
  95116. if (onError === void 0) { onError = null; }
  95117. if (buffer === void 0) { buffer = null; }
  95118. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95119. var url = String(urlArg);
  95120. texture.url = url;
  95121. texture.generateMipMaps = !noMipmap;
  95122. texture.samplingMode = samplingMode;
  95123. texture.invertY = invertY;
  95124. texture.baseWidth = this._options.textureSize;
  95125. texture.baseHeight = this._options.textureSize;
  95126. texture.width = this._options.textureSize;
  95127. texture.height = this._options.textureSize;
  95128. if (format) {
  95129. texture.format = format;
  95130. }
  95131. texture.isReady = true;
  95132. if (onLoad) {
  95133. onLoad();
  95134. }
  95135. return texture;
  95136. };
  95137. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95138. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95139. if (options !== undefined && typeof options === "object") {
  95140. fullOptions.generateMipMaps = options.generateMipMaps;
  95141. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95142. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95143. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95144. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95145. }
  95146. else {
  95147. fullOptions.generateMipMaps = options;
  95148. fullOptions.generateDepthBuffer = true;
  95149. fullOptions.generateStencilBuffer = false;
  95150. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95151. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95152. }
  95153. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95154. var width = size.width || size;
  95155. var height = size.height || size;
  95156. texture._depthStencilBuffer = {};
  95157. texture._framebuffer = {};
  95158. texture.baseWidth = width;
  95159. texture.baseHeight = height;
  95160. texture.width = width;
  95161. texture.height = height;
  95162. texture.isReady = true;
  95163. texture.samples = 1;
  95164. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95165. texture.samplingMode = fullOptions.samplingMode;
  95166. texture.type = fullOptions.type;
  95167. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95168. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95169. return texture;
  95170. };
  95171. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95172. texture.samplingMode = samplingMode;
  95173. };
  95174. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95175. if (this._currentRenderTarget) {
  95176. this.unBindFramebuffer(this._currentRenderTarget);
  95177. }
  95178. this._currentRenderTarget = texture;
  95179. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95180. if (this._cachedViewport && !forceFullscreenViewport) {
  95181. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95182. }
  95183. };
  95184. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95185. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95186. this._currentRenderTarget = null;
  95187. if (onBeforeUnbind) {
  95188. if (texture._MSAAFramebuffer) {
  95189. this._currentFramebuffer = texture._framebuffer;
  95190. }
  95191. onBeforeUnbind();
  95192. }
  95193. this._currentFramebuffer = null;
  95194. };
  95195. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95196. var vbo = {
  95197. capacity: 1,
  95198. references: 1,
  95199. is32Bits: false
  95200. };
  95201. return vbo;
  95202. };
  95203. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95204. if (offset === void 0) { offset = 0; }
  95205. };
  95206. /**
  95207. * Updates a dynamic vertex buffer.
  95208. * @param vertexBuffer the vertex buffer to update
  95209. * @param data the data used to update the vertex buffer
  95210. * @param byteOffset the byte offset of the data (optional)
  95211. * @param byteLength the byte length of the data (optional)
  95212. */
  95213. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95214. };
  95215. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95216. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95217. this._boundTexturesCache[this._activeChannel] = texture;
  95218. }
  95219. };
  95220. NullEngine.prototype._bindTexture = function (channel, texture) {
  95221. if (channel < 0) {
  95222. return;
  95223. }
  95224. this._bindTextureDirectly(0, texture);
  95225. };
  95226. NullEngine.prototype._releaseBuffer = function (buffer) {
  95227. buffer.references--;
  95228. if (buffer.references === 0) {
  95229. return true;
  95230. }
  95231. return false;
  95232. };
  95233. NullEngine.prototype.releaseEffects = function () {
  95234. };
  95235. return NullEngine;
  95236. }(BABYLON.Engine));
  95237. BABYLON.NullEngine = NullEngine;
  95238. })(BABYLON || (BABYLON = {}));
  95239. //# sourceMappingURL=babylon.nullEngine.js.map
  95240. var BABYLON;
  95241. (function (BABYLON) {
  95242. /**
  95243. * This class can be used to get instrumentation data from a Babylon engine
  95244. */
  95245. var EngineInstrumentation = /** @class */ (function () {
  95246. function EngineInstrumentation(engine) {
  95247. this.engine = engine;
  95248. this._captureGPUFrameTime = false;
  95249. this._gpuFrameTime = new BABYLON.PerfCounter();
  95250. this._captureShaderCompilationTime = false;
  95251. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95252. // Observers
  95253. this._onBeginFrameObserver = null;
  95254. this._onEndFrameObserver = null;
  95255. this._onBeforeShaderCompilationObserver = null;
  95256. this._onAfterShaderCompilationObserver = null;
  95257. }
  95258. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95259. // Properties
  95260. /**
  95261. * Gets the perf counter used for GPU frame time
  95262. */
  95263. get: function () {
  95264. return this._gpuFrameTime;
  95265. },
  95266. enumerable: true,
  95267. configurable: true
  95268. });
  95269. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95270. /**
  95271. * Gets the GPU frame time capture status
  95272. */
  95273. get: function () {
  95274. return this._captureGPUFrameTime;
  95275. },
  95276. /**
  95277. * Enable or disable the GPU frame time capture
  95278. */
  95279. set: function (value) {
  95280. var _this = this;
  95281. if (value === this._captureGPUFrameTime) {
  95282. return;
  95283. }
  95284. this._captureGPUFrameTime = value;
  95285. if (value) {
  95286. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95287. if (!_this._gpuFrameTimeToken) {
  95288. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95289. }
  95290. });
  95291. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95292. if (!_this._gpuFrameTimeToken) {
  95293. return;
  95294. }
  95295. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95296. if (time > -1) {
  95297. _this._gpuFrameTimeToken = null;
  95298. _this._gpuFrameTime.fetchNewFrame();
  95299. _this._gpuFrameTime.addCount(time, true);
  95300. }
  95301. });
  95302. }
  95303. else {
  95304. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95305. this._onBeginFrameObserver = null;
  95306. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95307. this._onEndFrameObserver = null;
  95308. }
  95309. },
  95310. enumerable: true,
  95311. configurable: true
  95312. });
  95313. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95314. /**
  95315. * Gets the perf counter used for shader compilation time
  95316. */
  95317. get: function () {
  95318. return this._shaderCompilationTime;
  95319. },
  95320. enumerable: true,
  95321. configurable: true
  95322. });
  95323. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95324. /**
  95325. * Gets the shader compilation time capture status
  95326. */
  95327. get: function () {
  95328. return this._captureShaderCompilationTime;
  95329. },
  95330. /**
  95331. * Enable or disable the shader compilation time capture
  95332. */
  95333. set: function (value) {
  95334. var _this = this;
  95335. if (value === this._captureShaderCompilationTime) {
  95336. return;
  95337. }
  95338. this._captureShaderCompilationTime = value;
  95339. if (value) {
  95340. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95341. _this._shaderCompilationTime.fetchNewFrame();
  95342. _this._shaderCompilationTime.beginMonitoring();
  95343. });
  95344. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95345. _this._shaderCompilationTime.endMonitoring();
  95346. });
  95347. }
  95348. else {
  95349. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95350. this._onBeforeShaderCompilationObserver = null;
  95351. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95352. this._onAfterShaderCompilationObserver = null;
  95353. }
  95354. },
  95355. enumerable: true,
  95356. configurable: true
  95357. });
  95358. EngineInstrumentation.prototype.dispose = function () {
  95359. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95360. this._onBeginFrameObserver = null;
  95361. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95362. this._onEndFrameObserver = null;
  95363. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95364. this._onBeforeShaderCompilationObserver = null;
  95365. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95366. this._onAfterShaderCompilationObserver = null;
  95367. this.engine = null;
  95368. };
  95369. return EngineInstrumentation;
  95370. }());
  95371. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95372. })(BABYLON || (BABYLON = {}));
  95373. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95374. var BABYLON;
  95375. (function (BABYLON) {
  95376. /**
  95377. * This class can be used to get instrumentation data from a Babylon engine
  95378. */
  95379. var SceneInstrumentation = /** @class */ (function () {
  95380. function SceneInstrumentation(scene) {
  95381. var _this = this;
  95382. this.scene = scene;
  95383. this._captureActiveMeshesEvaluationTime = false;
  95384. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95385. this._captureRenderTargetsRenderTime = false;
  95386. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95387. this._captureFrameTime = false;
  95388. this._frameTime = new BABYLON.PerfCounter();
  95389. this._captureRenderTime = false;
  95390. this._renderTime = new BABYLON.PerfCounter();
  95391. this._captureInterFrameTime = false;
  95392. this._interFrameTime = new BABYLON.PerfCounter();
  95393. this._captureParticlesRenderTime = false;
  95394. this._particlesRenderTime = new BABYLON.PerfCounter();
  95395. this._captureSpritesRenderTime = false;
  95396. this._spritesRenderTime = new BABYLON.PerfCounter();
  95397. this._capturePhysicsTime = false;
  95398. this._physicsTime = new BABYLON.PerfCounter();
  95399. this._captureAnimationsTime = false;
  95400. this._animationsTime = new BABYLON.PerfCounter();
  95401. // Observers
  95402. this._onBeforeActiveMeshesEvaluationObserver = null;
  95403. this._onAfterActiveMeshesEvaluationObserver = null;
  95404. this._onBeforeRenderTargetsRenderObserver = null;
  95405. this._onAfterRenderTargetsRenderObserver = null;
  95406. this._onAfterRenderObserver = null;
  95407. this._onBeforeDrawPhaseObserver = null;
  95408. this._onAfterDrawPhaseObserver = null;
  95409. this._onBeforeAnimationsObserver = null;
  95410. this._onBeforeParticlesRenderingObserver = null;
  95411. this._onAfterParticlesRenderingObserver = null;
  95412. this._onBeforeSpritesRenderingObserver = null;
  95413. this._onAfterSpritesRenderingObserver = null;
  95414. this._onBeforePhysicsObserver = null;
  95415. this._onAfterPhysicsObserver = null;
  95416. this._onAfterAnimationsObserver = null;
  95417. // Before render
  95418. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95419. if (_this._captureActiveMeshesEvaluationTime) {
  95420. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95421. }
  95422. if (_this._captureRenderTargetsRenderTime) {
  95423. _this._renderTargetsRenderTime.fetchNewFrame();
  95424. }
  95425. if (_this._captureFrameTime) {
  95426. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95427. _this._frameTime.beginMonitoring();
  95428. }
  95429. if (_this._captureInterFrameTime) {
  95430. _this._interFrameTime.endMonitoring();
  95431. }
  95432. if (_this._captureParticlesRenderTime) {
  95433. _this._particlesRenderTime.fetchNewFrame();
  95434. }
  95435. if (_this._captureSpritesRenderTime) {
  95436. _this._spritesRenderTime.fetchNewFrame();
  95437. }
  95438. if (_this._captureAnimationsTime) {
  95439. _this._animationsTime.beginMonitoring();
  95440. }
  95441. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95442. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95443. });
  95444. // After render
  95445. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95446. if (_this._captureFrameTime) {
  95447. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95448. _this._frameTime.endMonitoring();
  95449. }
  95450. if (_this._captureRenderTime) {
  95451. _this._renderTime.endMonitoring(false);
  95452. }
  95453. if (_this._captureInterFrameTime) {
  95454. _this._interFrameTime.beginMonitoring();
  95455. }
  95456. });
  95457. }
  95458. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95459. // Properties
  95460. /**
  95461. * Gets the perf counter used for active meshes evaluation time
  95462. */
  95463. get: function () {
  95464. return this._activeMeshesEvaluationTime;
  95465. },
  95466. enumerable: true,
  95467. configurable: true
  95468. });
  95469. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95470. /**
  95471. * Gets the active meshes evaluation time capture status
  95472. */
  95473. get: function () {
  95474. return this._captureActiveMeshesEvaluationTime;
  95475. },
  95476. /**
  95477. * Enable or disable the active meshes evaluation time capture
  95478. */
  95479. set: function (value) {
  95480. var _this = this;
  95481. if (value === this._captureActiveMeshesEvaluationTime) {
  95482. return;
  95483. }
  95484. this._captureActiveMeshesEvaluationTime = value;
  95485. if (value) {
  95486. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95487. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95488. _this._activeMeshesEvaluationTime.beginMonitoring();
  95489. });
  95490. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95491. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95492. _this._activeMeshesEvaluationTime.endMonitoring();
  95493. });
  95494. }
  95495. else {
  95496. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95497. this._onBeforeActiveMeshesEvaluationObserver = null;
  95498. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95499. this._onAfterActiveMeshesEvaluationObserver = null;
  95500. }
  95501. },
  95502. enumerable: true,
  95503. configurable: true
  95504. });
  95505. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95506. /**
  95507. * Gets the perf counter used for render targets render time
  95508. */
  95509. get: function () {
  95510. return this._renderTargetsRenderTime;
  95511. },
  95512. enumerable: true,
  95513. configurable: true
  95514. });
  95515. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95516. /**
  95517. * Gets the render targets render time capture status
  95518. */
  95519. get: function () {
  95520. return this._captureRenderTargetsRenderTime;
  95521. },
  95522. /**
  95523. * Enable or disable the render targets render time capture
  95524. */
  95525. set: function (value) {
  95526. var _this = this;
  95527. if (value === this._captureRenderTargetsRenderTime) {
  95528. return;
  95529. }
  95530. this._captureRenderTargetsRenderTime = value;
  95531. if (value) {
  95532. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95533. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95534. _this._renderTargetsRenderTime.beginMonitoring();
  95535. });
  95536. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95537. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95538. _this._renderTargetsRenderTime.endMonitoring(false);
  95539. });
  95540. }
  95541. else {
  95542. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95543. this._onBeforeRenderTargetsRenderObserver = null;
  95544. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95545. this._onAfterRenderTargetsRenderObserver = null;
  95546. }
  95547. },
  95548. enumerable: true,
  95549. configurable: true
  95550. });
  95551. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95552. /**
  95553. * Gets the perf counter used for particles render time
  95554. */
  95555. get: function () {
  95556. return this._particlesRenderTime;
  95557. },
  95558. enumerable: true,
  95559. configurable: true
  95560. });
  95561. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95562. /**
  95563. * Gets the particles render time capture status
  95564. */
  95565. get: function () {
  95566. return this._captureParticlesRenderTime;
  95567. },
  95568. /**
  95569. * Enable or disable the particles render time capture
  95570. */
  95571. set: function (value) {
  95572. var _this = this;
  95573. if (value === this._captureParticlesRenderTime) {
  95574. return;
  95575. }
  95576. this._captureParticlesRenderTime = value;
  95577. if (value) {
  95578. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95579. BABYLON.Tools.StartPerformanceCounter("Particles");
  95580. _this._particlesRenderTime.beginMonitoring();
  95581. });
  95582. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95583. BABYLON.Tools.EndPerformanceCounter("Particles");
  95584. _this._particlesRenderTime.endMonitoring(false);
  95585. });
  95586. }
  95587. else {
  95588. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95589. this._onBeforeParticlesRenderingObserver = null;
  95590. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95591. this._onAfterParticlesRenderingObserver = null;
  95592. }
  95593. },
  95594. enumerable: true,
  95595. configurable: true
  95596. });
  95597. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95598. /**
  95599. * Gets the perf counter used for sprites render time
  95600. */
  95601. get: function () {
  95602. return this._spritesRenderTime;
  95603. },
  95604. enumerable: true,
  95605. configurable: true
  95606. });
  95607. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95608. /**
  95609. * Gets the sprites render time capture status
  95610. */
  95611. get: function () {
  95612. return this._captureSpritesRenderTime;
  95613. },
  95614. /**
  95615. * Enable or disable the sprites render time capture
  95616. */
  95617. set: function (value) {
  95618. var _this = this;
  95619. if (value === this._captureSpritesRenderTime) {
  95620. return;
  95621. }
  95622. this._captureSpritesRenderTime = value;
  95623. if (value) {
  95624. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95625. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95626. _this._spritesRenderTime.beginMonitoring();
  95627. });
  95628. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95629. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95630. _this._spritesRenderTime.endMonitoring(false);
  95631. });
  95632. }
  95633. else {
  95634. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95635. this._onBeforeSpritesRenderingObserver = null;
  95636. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95637. this._onAfterSpritesRenderingObserver = null;
  95638. }
  95639. },
  95640. enumerable: true,
  95641. configurable: true
  95642. });
  95643. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95644. /**
  95645. * Gets the perf counter used for physics time
  95646. */
  95647. get: function () {
  95648. return this._physicsTime;
  95649. },
  95650. enumerable: true,
  95651. configurable: true
  95652. });
  95653. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95654. /**
  95655. * Gets the physics time capture status
  95656. */
  95657. get: function () {
  95658. return this._capturePhysicsTime;
  95659. },
  95660. /**
  95661. * Enable or disable the physics time capture
  95662. */
  95663. set: function (value) {
  95664. var _this = this;
  95665. if (value === this._capturePhysicsTime) {
  95666. return;
  95667. }
  95668. this._capturePhysicsTime = value;
  95669. if (value) {
  95670. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95671. BABYLON.Tools.StartPerformanceCounter("Physics");
  95672. _this._physicsTime.beginMonitoring();
  95673. });
  95674. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95675. BABYLON.Tools.EndPerformanceCounter("Physics");
  95676. _this._physicsTime.endMonitoring();
  95677. });
  95678. }
  95679. else {
  95680. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95681. this._onBeforePhysicsObserver = null;
  95682. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95683. this._onAfterPhysicsObserver = null;
  95684. }
  95685. },
  95686. enumerable: true,
  95687. configurable: true
  95688. });
  95689. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95690. /**
  95691. * Gets the perf counter used for animations time
  95692. */
  95693. get: function () {
  95694. return this._animationsTime;
  95695. },
  95696. enumerable: true,
  95697. configurable: true
  95698. });
  95699. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95700. /**
  95701. * Gets the animations time capture status
  95702. */
  95703. get: function () {
  95704. return this._captureAnimationsTime;
  95705. },
  95706. /**
  95707. * Enable or disable the animations time capture
  95708. */
  95709. set: function (value) {
  95710. var _this = this;
  95711. if (value === this._captureAnimationsTime) {
  95712. return;
  95713. }
  95714. this._captureAnimationsTime = value;
  95715. if (value) {
  95716. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95717. _this._animationsTime.endMonitoring();
  95718. });
  95719. }
  95720. else {
  95721. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95722. this._onAfterAnimationsObserver = null;
  95723. }
  95724. },
  95725. enumerable: true,
  95726. configurable: true
  95727. });
  95728. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95729. /**
  95730. * Gets the perf counter used for frame time capture
  95731. */
  95732. get: function () {
  95733. return this._frameTime;
  95734. },
  95735. enumerable: true,
  95736. configurable: true
  95737. });
  95738. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95739. /**
  95740. * Gets the frame time capture status
  95741. */
  95742. get: function () {
  95743. return this._captureFrameTime;
  95744. },
  95745. /**
  95746. * Enable or disable the frame time capture
  95747. */
  95748. set: function (value) {
  95749. this._captureFrameTime = value;
  95750. },
  95751. enumerable: true,
  95752. configurable: true
  95753. });
  95754. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95755. /**
  95756. * Gets the perf counter used for inter-frames time capture
  95757. */
  95758. get: function () {
  95759. return this._interFrameTime;
  95760. },
  95761. enumerable: true,
  95762. configurable: true
  95763. });
  95764. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95765. /**
  95766. * Gets the inter-frames time capture status
  95767. */
  95768. get: function () {
  95769. return this._captureInterFrameTime;
  95770. },
  95771. /**
  95772. * Enable or disable the inter-frames time capture
  95773. */
  95774. set: function (value) {
  95775. this._captureInterFrameTime = value;
  95776. },
  95777. enumerable: true,
  95778. configurable: true
  95779. });
  95780. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95781. /**
  95782. * Gets the perf counter used for render time capture
  95783. */
  95784. get: function () {
  95785. return this._renderTime;
  95786. },
  95787. enumerable: true,
  95788. configurable: true
  95789. });
  95790. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95791. /**
  95792. * Gets the render time capture status
  95793. */
  95794. get: function () {
  95795. return this._captureRenderTime;
  95796. },
  95797. /**
  95798. * Enable or disable the render time capture
  95799. */
  95800. set: function (value) {
  95801. var _this = this;
  95802. if (value === this._captureRenderTime) {
  95803. return;
  95804. }
  95805. this._captureRenderTime = value;
  95806. if (value) {
  95807. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95808. _this._renderTime.beginMonitoring();
  95809. BABYLON.Tools.StartPerformanceCounter("Main render");
  95810. });
  95811. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95812. _this._renderTime.endMonitoring(false);
  95813. BABYLON.Tools.EndPerformanceCounter("Main render");
  95814. });
  95815. }
  95816. else {
  95817. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95818. this._onBeforeDrawPhaseObserver = null;
  95819. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95820. this._onAfterDrawPhaseObserver = null;
  95821. }
  95822. },
  95823. enumerable: true,
  95824. configurable: true
  95825. });
  95826. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95827. /**
  95828. * Gets the perf counter used for draw calls
  95829. */
  95830. get: function () {
  95831. return this.scene.getEngine()._drawCalls;
  95832. },
  95833. enumerable: true,
  95834. configurable: true
  95835. });
  95836. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95837. /**
  95838. * Gets the perf counter used for texture collisions
  95839. */
  95840. get: function () {
  95841. return this.scene.getEngine()._textureCollisions;
  95842. },
  95843. enumerable: true,
  95844. configurable: true
  95845. });
  95846. SceneInstrumentation.prototype.dispose = function () {
  95847. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95848. this._onAfterRenderObserver = null;
  95849. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95850. this._onBeforeActiveMeshesEvaluationObserver = null;
  95851. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95852. this._onAfterActiveMeshesEvaluationObserver = null;
  95853. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95854. this._onBeforeRenderTargetsRenderObserver = null;
  95855. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95856. this._onAfterRenderTargetsRenderObserver = null;
  95857. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95858. this._onBeforeAnimationsObserver = null;
  95859. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95860. this._onBeforeParticlesRenderingObserver = null;
  95861. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95862. this._onAfterParticlesRenderingObserver = null;
  95863. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95864. this._onBeforeSpritesRenderingObserver = null;
  95865. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95866. this._onAfterSpritesRenderingObserver = null;
  95867. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95868. this._onBeforeDrawPhaseObserver = null;
  95869. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95870. this._onAfterDrawPhaseObserver = null;
  95871. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95872. this._onBeforePhysicsObserver = null;
  95873. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95874. this._onAfterPhysicsObserver = null;
  95875. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95876. this._onAfterAnimationsObserver = null;
  95877. this.scene = null;
  95878. };
  95879. return SceneInstrumentation;
  95880. }());
  95881. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95882. })(BABYLON || (BABYLON = {}));
  95883. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95884. var BABYLON;
  95885. (function (BABYLON) {
  95886. /**
  95887. * @hidden
  95888. **/
  95889. var _TimeToken = /** @class */ (function () {
  95890. function _TimeToken() {
  95891. this._timeElapsedQueryEnded = false;
  95892. }
  95893. return _TimeToken;
  95894. }());
  95895. BABYLON._TimeToken = _TimeToken;
  95896. })(BABYLON || (BABYLON = {}));
  95897. //# sourceMappingURL=babylon.timeToken.js.map
  95898. var BABYLON;
  95899. (function (BABYLON) {
  95900. /**
  95901. * Background material defines definition.
  95902. * @hidden Mainly internal Use
  95903. */
  95904. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95905. __extends(BackgroundMaterialDefines, _super);
  95906. /**
  95907. * Constructor of the defines.
  95908. */
  95909. function BackgroundMaterialDefines() {
  95910. var _this = _super.call(this) || this;
  95911. /**
  95912. * True if the diffuse texture is in use.
  95913. */
  95914. _this.DIFFUSE = false;
  95915. /**
  95916. * The direct UV channel to use.
  95917. */
  95918. _this.DIFFUSEDIRECTUV = 0;
  95919. /**
  95920. * True if the diffuse texture is in gamma space.
  95921. */
  95922. _this.GAMMADIFFUSE = false;
  95923. /**
  95924. * True if the diffuse texture has opacity in the alpha channel.
  95925. */
  95926. _this.DIFFUSEHASALPHA = false;
  95927. /**
  95928. * True if you want the material to fade to transparent at grazing angle.
  95929. */
  95930. _this.OPACITYFRESNEL = false;
  95931. /**
  95932. * True if an extra blur needs to be added in the reflection.
  95933. */
  95934. _this.REFLECTIONBLUR = false;
  95935. /**
  95936. * True if you want the material to fade to reflection at grazing angle.
  95937. */
  95938. _this.REFLECTIONFRESNEL = false;
  95939. /**
  95940. * True if you want the material to falloff as far as you move away from the scene center.
  95941. */
  95942. _this.REFLECTIONFALLOFF = false;
  95943. /**
  95944. * False if the current Webgl implementation does not support the texture lod extension.
  95945. */
  95946. _this.TEXTURELODSUPPORT = false;
  95947. /**
  95948. * True to ensure the data are premultiplied.
  95949. */
  95950. _this.PREMULTIPLYALPHA = false;
  95951. /**
  95952. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95953. */
  95954. _this.USERGBCOLOR = false;
  95955. /**
  95956. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95957. * stays aligned with the desired configuration.
  95958. */
  95959. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95960. /**
  95961. * True to add noise in order to reduce the banding effect.
  95962. */
  95963. _this.NOISE = false;
  95964. /**
  95965. * is the reflection texture in BGR color scheme?
  95966. * Mainly used to solve a bug in ios10 video tag
  95967. */
  95968. _this.REFLECTIONBGR = false;
  95969. _this.IMAGEPROCESSING = false;
  95970. _this.VIGNETTE = false;
  95971. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95972. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95973. _this.TONEMAPPING = false;
  95974. _this.CONTRAST = false;
  95975. _this.COLORCURVES = false;
  95976. _this.COLORGRADING = false;
  95977. _this.COLORGRADING3D = false;
  95978. _this.SAMPLER3DGREENDEPTH = false;
  95979. _this.SAMPLER3DBGRMAP = false;
  95980. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95981. _this.EXPOSURE = false;
  95982. // Reflection.
  95983. _this.REFLECTION = false;
  95984. _this.REFLECTIONMAP_3D = false;
  95985. _this.REFLECTIONMAP_SPHERICAL = false;
  95986. _this.REFLECTIONMAP_PLANAR = false;
  95987. _this.REFLECTIONMAP_CUBIC = false;
  95988. _this.REFLECTIONMAP_PROJECTION = false;
  95989. _this.REFLECTIONMAP_SKYBOX = false;
  95990. _this.REFLECTIONMAP_EXPLICIT = false;
  95991. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95992. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95993. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95994. _this.INVERTCUBICMAP = false;
  95995. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95996. _this.LODINREFLECTIONALPHA = false;
  95997. _this.GAMMAREFLECTION = false;
  95998. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95999. // Default BJS.
  96000. _this.MAINUV1 = false;
  96001. _this.MAINUV2 = false;
  96002. _this.UV1 = false;
  96003. _this.UV2 = false;
  96004. _this.CLIPPLANE = false;
  96005. _this.POINTSIZE = false;
  96006. _this.FOG = false;
  96007. _this.NORMAL = false;
  96008. _this.NUM_BONE_INFLUENCERS = 0;
  96009. _this.BonesPerMesh = 0;
  96010. _this.INSTANCES = false;
  96011. _this.SHADOWFLOAT = false;
  96012. _this.rebuild();
  96013. return _this;
  96014. }
  96015. return BackgroundMaterialDefines;
  96016. }(BABYLON.MaterialDefines));
  96017. /**
  96018. * Background material used to create an efficient environement around your scene.
  96019. */
  96020. var BackgroundMaterial = /** @class */ (function (_super) {
  96021. __extends(BackgroundMaterial, _super);
  96022. /**
  96023. * Instantiates a Background Material in the given scene
  96024. * @param name The friendly name of the material
  96025. * @param scene The scene to add the material to
  96026. */
  96027. function BackgroundMaterial(name, scene) {
  96028. var _this = _super.call(this, name, scene) || this;
  96029. /**
  96030. * Key light Color (multiply against the environement texture)
  96031. */
  96032. _this.primaryColor = BABYLON.Color3.White();
  96033. _this._primaryColorShadowLevel = 0;
  96034. _this._primaryColorHighlightLevel = 0;
  96035. /**
  96036. * Reflection Texture used in the material.
  96037. * Should be author in a specific way for the best result (refer to the documentation).
  96038. */
  96039. _this.reflectionTexture = null;
  96040. /**
  96041. * Reflection Texture level of blur.
  96042. *
  96043. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96044. * texture twice.
  96045. */
  96046. _this.reflectionBlur = 0;
  96047. /**
  96048. * Diffuse Texture used in the material.
  96049. * Should be author in a specific way for the best result (refer to the documentation).
  96050. */
  96051. _this.diffuseTexture = null;
  96052. _this._shadowLights = null;
  96053. /**
  96054. * Specify the list of lights casting shadow on the material.
  96055. * All scene shadow lights will be included if null.
  96056. */
  96057. _this.shadowLights = null;
  96058. /**
  96059. * Helps adjusting the shadow to a softer level if required.
  96060. * 0 means black shadows and 1 means no shadows.
  96061. */
  96062. _this.shadowLevel = 0;
  96063. /**
  96064. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96065. * It is usually zero but might be interesting to modify according to your setup.
  96066. */
  96067. _this.sceneCenter = BABYLON.Vector3.Zero();
  96068. /**
  96069. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96070. * This helps ensuring a nice transition when the camera goes under the ground.
  96071. */
  96072. _this.opacityFresnel = true;
  96073. /**
  96074. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96075. * This helps adding a mirror texture on the ground.
  96076. */
  96077. _this.reflectionFresnel = false;
  96078. /**
  96079. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96080. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96081. */
  96082. _this.reflectionFalloffDistance = 0.0;
  96083. /**
  96084. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96085. */
  96086. _this.reflectionAmount = 1.0;
  96087. /**
  96088. * This specifies the weight of the reflection at grazing angle.
  96089. */
  96090. _this.reflectionReflectance0 = 0.05;
  96091. /**
  96092. * This specifies the weight of the reflection at a perpendicular point of view.
  96093. */
  96094. _this.reflectionReflectance90 = 0.5;
  96095. /**
  96096. * Helps to directly use the maps channels instead of their level.
  96097. */
  96098. _this.useRGBColor = true;
  96099. /**
  96100. * This helps reducing the banding effect that could occur on the background.
  96101. */
  96102. _this.enableNoise = false;
  96103. _this._fovMultiplier = 1.0;
  96104. /**
  96105. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96106. */
  96107. _this.useEquirectangularFOV = false;
  96108. _this._maxSimultaneousLights = 4;
  96109. /**
  96110. * Number of Simultaneous lights allowed on the material.
  96111. */
  96112. _this.maxSimultaneousLights = 4;
  96113. /**
  96114. * Keep track of the image processing observer to allow dispose and replace.
  96115. */
  96116. _this._imageProcessingObserver = null;
  96117. /**
  96118. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96119. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96120. */
  96121. _this.switchToBGR = false;
  96122. // Temp values kept as cache in the material.
  96123. _this._renderTargets = new BABYLON.SmartArray(16);
  96124. _this._reflectionControls = BABYLON.Vector4.Zero();
  96125. _this._white = BABYLON.Color3.White();
  96126. _this._primaryShadowColor = BABYLON.Color3.Black();
  96127. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96128. // Setup the default processing configuration to the scene.
  96129. _this._attachImageProcessingConfiguration(null);
  96130. _this.getRenderTargetTextures = function () {
  96131. _this._renderTargets.reset();
  96132. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96133. _this._renderTargets.push(_this._diffuseTexture);
  96134. }
  96135. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96136. _this._renderTargets.push(_this._reflectionTexture);
  96137. }
  96138. return _this._renderTargets;
  96139. };
  96140. return _this;
  96141. }
  96142. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96143. /**
  96144. * Experimental Internal Use Only.
  96145. *
  96146. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96147. * This acts as a helper to set the primary color to a more "human friendly" value.
  96148. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96149. * output color as close as possible from the chosen value.
  96150. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96151. * part of lighting setup.)
  96152. */
  96153. get: function () {
  96154. return this.__perceptualColor;
  96155. },
  96156. set: function (value) {
  96157. this.__perceptualColor = value;
  96158. this._computePrimaryColorFromPerceptualColor();
  96159. this._markAllSubMeshesAsLightsDirty();
  96160. },
  96161. enumerable: true,
  96162. configurable: true
  96163. });
  96164. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96165. /**
  96166. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96167. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96168. */
  96169. get: function () {
  96170. return this._primaryColorShadowLevel;
  96171. },
  96172. set: function (value) {
  96173. this._primaryColorShadowLevel = value;
  96174. this._computePrimaryColors();
  96175. this._markAllSubMeshesAsLightsDirty();
  96176. },
  96177. enumerable: true,
  96178. configurable: true
  96179. });
  96180. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96181. /**
  96182. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96183. * The primary color is used at the level chosen to define what the white area would look.
  96184. */
  96185. get: function () {
  96186. return this._primaryColorHighlightLevel;
  96187. },
  96188. set: function (value) {
  96189. this._primaryColorHighlightLevel = value;
  96190. this._computePrimaryColors();
  96191. this._markAllSubMeshesAsLightsDirty();
  96192. },
  96193. enumerable: true,
  96194. configurable: true
  96195. });
  96196. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96197. /**
  96198. * Sets the reflection reflectance fresnel values according to the default standard
  96199. * empirically know to work well :-)
  96200. */
  96201. set: function (value) {
  96202. var reflectionWeight = value;
  96203. if (reflectionWeight < 0.5) {
  96204. reflectionWeight = reflectionWeight * 2.0;
  96205. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96206. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96207. }
  96208. else {
  96209. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96210. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96211. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96212. }
  96213. },
  96214. enumerable: true,
  96215. configurable: true
  96216. });
  96217. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96218. /**
  96219. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96220. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96221. * Recommended to be keep at 1.0 except for special cases.
  96222. */
  96223. get: function () {
  96224. return this._fovMultiplier;
  96225. },
  96226. set: function (value) {
  96227. if (isNaN(value)) {
  96228. value = 1.0;
  96229. }
  96230. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96231. },
  96232. enumerable: true,
  96233. configurable: true
  96234. });
  96235. /**
  96236. * Attaches a new image processing configuration to the PBR Material.
  96237. * @param configuration (if null the scene configuration will be use)
  96238. */
  96239. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96240. var _this = this;
  96241. if (configuration === this._imageProcessingConfiguration) {
  96242. return;
  96243. }
  96244. // Detaches observer.
  96245. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96246. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96247. }
  96248. // Pick the scene configuration if needed.
  96249. if (!configuration) {
  96250. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96251. }
  96252. else {
  96253. this._imageProcessingConfiguration = configuration;
  96254. }
  96255. // Attaches observer.
  96256. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96257. _this._computePrimaryColorFromPerceptualColor();
  96258. _this._markAllSubMeshesAsImageProcessingDirty();
  96259. });
  96260. };
  96261. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96262. /**
  96263. * Gets the image processing configuration used either in this material.
  96264. */
  96265. get: function () {
  96266. return this._imageProcessingConfiguration;
  96267. },
  96268. /**
  96269. * Sets the Default image processing configuration used either in the this material.
  96270. *
  96271. * If sets to null, the scene one is in use.
  96272. */
  96273. set: function (value) {
  96274. this._attachImageProcessingConfiguration(value);
  96275. // Ensure the effect will be rebuilt.
  96276. this._markAllSubMeshesAsTexturesDirty();
  96277. },
  96278. enumerable: true,
  96279. configurable: true
  96280. });
  96281. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96282. /**
  96283. * Gets wether the color curves effect is enabled.
  96284. */
  96285. get: function () {
  96286. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96287. },
  96288. /**
  96289. * Sets wether the color curves effect is enabled.
  96290. */
  96291. set: function (value) {
  96292. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96293. },
  96294. enumerable: true,
  96295. configurable: true
  96296. });
  96297. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96298. /**
  96299. * Gets wether the color grading effect is enabled.
  96300. */
  96301. get: function () {
  96302. return this.imageProcessingConfiguration.colorGradingEnabled;
  96303. },
  96304. /**
  96305. * Gets wether the color grading effect is enabled.
  96306. */
  96307. set: function (value) {
  96308. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96309. },
  96310. enumerable: true,
  96311. configurable: true
  96312. });
  96313. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96314. /**
  96315. * Gets wether tonemapping is enabled or not.
  96316. */
  96317. get: function () {
  96318. return this._imageProcessingConfiguration.toneMappingEnabled;
  96319. },
  96320. /**
  96321. * Sets wether tonemapping is enabled or not
  96322. */
  96323. set: function (value) {
  96324. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96325. },
  96326. enumerable: true,
  96327. configurable: true
  96328. });
  96329. ;
  96330. ;
  96331. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96332. /**
  96333. * The camera exposure used on this material.
  96334. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96335. * This corresponds to a photographic exposure.
  96336. */
  96337. get: function () {
  96338. return this._imageProcessingConfiguration.exposure;
  96339. },
  96340. /**
  96341. * The camera exposure used on this material.
  96342. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96343. * This corresponds to a photographic exposure.
  96344. */
  96345. set: function (value) {
  96346. this._imageProcessingConfiguration.exposure = value;
  96347. },
  96348. enumerable: true,
  96349. configurable: true
  96350. });
  96351. ;
  96352. ;
  96353. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96354. /**
  96355. * Gets The camera contrast used on this material.
  96356. */
  96357. get: function () {
  96358. return this._imageProcessingConfiguration.contrast;
  96359. },
  96360. /**
  96361. * Sets The camera contrast used on this material.
  96362. */
  96363. set: function (value) {
  96364. this._imageProcessingConfiguration.contrast = value;
  96365. },
  96366. enumerable: true,
  96367. configurable: true
  96368. });
  96369. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96370. /**
  96371. * Gets the Color Grading 2D Lookup Texture.
  96372. */
  96373. get: function () {
  96374. return this._imageProcessingConfiguration.colorGradingTexture;
  96375. },
  96376. /**
  96377. * Sets the Color Grading 2D Lookup Texture.
  96378. */
  96379. set: function (value) {
  96380. this.imageProcessingConfiguration.colorGradingTexture = value;
  96381. },
  96382. enumerable: true,
  96383. configurable: true
  96384. });
  96385. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96386. /**
  96387. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96388. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96389. * 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;
  96390. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96391. */
  96392. get: function () {
  96393. return this.imageProcessingConfiguration.colorCurves;
  96394. },
  96395. /**
  96396. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96397. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96398. * 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;
  96399. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96400. */
  96401. set: function (value) {
  96402. this.imageProcessingConfiguration.colorCurves = value;
  96403. },
  96404. enumerable: true,
  96405. configurable: true
  96406. });
  96407. /**
  96408. * The entire material has been created in order to prevent overdraw.
  96409. * @returns false
  96410. */
  96411. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96412. return true;
  96413. };
  96414. /**
  96415. * The entire material has been created in order to prevent overdraw.
  96416. * @returns true if blending is enable
  96417. */
  96418. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96419. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96420. };
  96421. /**
  96422. * Checks wether the material is ready to be rendered for a given mesh.
  96423. * @param mesh The mesh to render
  96424. * @param subMesh The submesh to check against
  96425. * @param useInstances Specify wether or not the material is used with instances
  96426. * @returns true if all the dependencies are ready (Textures, Effects...)
  96427. */
  96428. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96429. var _this = this;
  96430. if (useInstances === void 0) { useInstances = false; }
  96431. if (subMesh.effect && this.isFrozen) {
  96432. if (this._wasPreviouslyReady) {
  96433. return true;
  96434. }
  96435. }
  96436. if (!subMesh._materialDefines) {
  96437. subMesh._materialDefines = new BackgroundMaterialDefines();
  96438. }
  96439. var scene = this.getScene();
  96440. var defines = subMesh._materialDefines;
  96441. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96442. if (defines._renderId === scene.getRenderId()) {
  96443. return true;
  96444. }
  96445. }
  96446. var engine = scene.getEngine();
  96447. // Lights
  96448. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96449. defines._needNormals = true;
  96450. // Textures
  96451. if (defines._areTexturesDirty) {
  96452. defines._needUVs = false;
  96453. if (scene.texturesEnabled) {
  96454. if (scene.getEngine().getCaps().textureLOD) {
  96455. defines.TEXTURELODSUPPORT = true;
  96456. }
  96457. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96458. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96459. return false;
  96460. }
  96461. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96462. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96463. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96464. defines.OPACITYFRESNEL = this._opacityFresnel;
  96465. }
  96466. else {
  96467. defines.DIFFUSE = false;
  96468. defines.DIFFUSEHASALPHA = false;
  96469. defines.GAMMADIFFUSE = false;
  96470. defines.OPACITYFRESNEL = false;
  96471. }
  96472. var reflectionTexture = this._reflectionTexture;
  96473. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96474. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96475. return false;
  96476. }
  96477. defines.REFLECTION = true;
  96478. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96479. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96480. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96481. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96482. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96483. defines.REFLECTIONBGR = this.switchToBGR;
  96484. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96485. defines.INVERTCUBICMAP = true;
  96486. }
  96487. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96488. switch (reflectionTexture.coordinatesMode) {
  96489. case BABYLON.Texture.EXPLICIT_MODE:
  96490. defines.REFLECTIONMAP_EXPLICIT = true;
  96491. break;
  96492. case BABYLON.Texture.PLANAR_MODE:
  96493. defines.REFLECTIONMAP_PLANAR = true;
  96494. break;
  96495. case BABYLON.Texture.PROJECTION_MODE:
  96496. defines.REFLECTIONMAP_PROJECTION = true;
  96497. break;
  96498. case BABYLON.Texture.SKYBOX_MODE:
  96499. defines.REFLECTIONMAP_SKYBOX = true;
  96500. break;
  96501. case BABYLON.Texture.SPHERICAL_MODE:
  96502. defines.REFLECTIONMAP_SPHERICAL = true;
  96503. break;
  96504. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96505. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96506. break;
  96507. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96508. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96509. break;
  96510. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96511. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96512. break;
  96513. case BABYLON.Texture.CUBIC_MODE:
  96514. case BABYLON.Texture.INVCUBIC_MODE:
  96515. default:
  96516. defines.REFLECTIONMAP_CUBIC = true;
  96517. break;
  96518. }
  96519. if (this.reflectionFresnel) {
  96520. defines.REFLECTIONFRESNEL = true;
  96521. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96522. this._reflectionControls.x = this.reflectionAmount;
  96523. this._reflectionControls.y = this.reflectionReflectance0;
  96524. this._reflectionControls.z = this.reflectionReflectance90;
  96525. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96526. }
  96527. else {
  96528. defines.REFLECTIONFRESNEL = false;
  96529. defines.REFLECTIONFALLOFF = false;
  96530. }
  96531. }
  96532. else {
  96533. defines.REFLECTION = false;
  96534. defines.REFLECTIONFRESNEL = false;
  96535. defines.REFLECTIONFALLOFF = false;
  96536. defines.REFLECTIONBLUR = false;
  96537. defines.REFLECTIONMAP_3D = false;
  96538. defines.REFLECTIONMAP_SPHERICAL = false;
  96539. defines.REFLECTIONMAP_PLANAR = false;
  96540. defines.REFLECTIONMAP_CUBIC = false;
  96541. defines.REFLECTIONMAP_PROJECTION = false;
  96542. defines.REFLECTIONMAP_SKYBOX = false;
  96543. defines.REFLECTIONMAP_EXPLICIT = false;
  96544. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96545. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96546. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96547. defines.INVERTCUBICMAP = false;
  96548. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96549. defines.LODINREFLECTIONALPHA = false;
  96550. defines.GAMMAREFLECTION = false;
  96551. }
  96552. }
  96553. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96554. defines.USERGBCOLOR = this._useRGBColor;
  96555. defines.NOISE = this._enableNoise;
  96556. }
  96557. if (defines._areLightsDirty) {
  96558. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96559. }
  96560. if (defines._areImageProcessingDirty) {
  96561. if (!this._imageProcessingConfiguration.isReady()) {
  96562. return false;
  96563. }
  96564. this._imageProcessingConfiguration.prepareDefines(defines);
  96565. }
  96566. // Misc.
  96567. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96568. // Values that need to be evaluated on every frame
  96569. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96570. // Attribs
  96571. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96572. if (mesh) {
  96573. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96574. mesh.createNormals(true);
  96575. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96576. }
  96577. }
  96578. }
  96579. // Get correct effect
  96580. if (defines.isDirty) {
  96581. defines.markAsProcessed();
  96582. scene.resetCachedMaterial();
  96583. // Fallbacks
  96584. var fallbacks = new BABYLON.EffectFallbacks();
  96585. if (defines.FOG) {
  96586. fallbacks.addFallback(0, "FOG");
  96587. }
  96588. if (defines.POINTSIZE) {
  96589. fallbacks.addFallback(1, "POINTSIZE");
  96590. }
  96591. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96592. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96593. fallbacks.addCPUSkinningFallback(0, mesh);
  96594. }
  96595. //Attributes
  96596. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96597. if (defines.NORMAL) {
  96598. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96599. }
  96600. if (defines.UV1) {
  96601. attribs.push(BABYLON.VertexBuffer.UVKind);
  96602. }
  96603. if (defines.UV2) {
  96604. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96605. }
  96606. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96607. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96608. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96609. "vFogInfos", "vFogColor", "pointSize",
  96610. "vClipPlane", "mBones",
  96611. "vPrimaryColor", "vPrimaryColorShadow",
  96612. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96613. "shadowLevel", "alpha",
  96614. "vBackgroundCenter", "vReflectionControl",
  96615. "vDiffuseInfos", "diffuseMatrix",
  96616. ];
  96617. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96618. var uniformBuffers = ["Material", "Scene"];
  96619. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96620. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96621. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96622. uniformsNames: uniforms,
  96623. uniformBuffersNames: uniformBuffers,
  96624. samplers: samplers,
  96625. defines: defines,
  96626. maxSimultaneousLights: this._maxSimultaneousLights
  96627. });
  96628. var onCompiled = function (effect) {
  96629. if (_this.onCompiled) {
  96630. _this.onCompiled(effect);
  96631. }
  96632. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96633. };
  96634. var join = defines.toString();
  96635. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96636. attributes: attribs,
  96637. uniformsNames: uniforms,
  96638. uniformBuffersNames: uniformBuffers,
  96639. samplers: samplers,
  96640. defines: join,
  96641. fallbacks: fallbacks,
  96642. onCompiled: onCompiled,
  96643. onError: this.onError,
  96644. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96645. }, engine), defines);
  96646. this.buildUniformLayout();
  96647. }
  96648. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96649. return false;
  96650. }
  96651. defines._renderId = scene.getRenderId();
  96652. this._wasPreviouslyReady = true;
  96653. return true;
  96654. };
  96655. /**
  96656. * Compute the primary color according to the chosen perceptual color.
  96657. */
  96658. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96659. if (!this.__perceptualColor) {
  96660. return;
  96661. }
  96662. this._primaryColor.copyFrom(this.__perceptualColor);
  96663. // Revert gamma space.
  96664. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96665. // Revert image processing configuration.
  96666. if (this._imageProcessingConfiguration) {
  96667. // Revert Exposure.
  96668. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96669. }
  96670. this._computePrimaryColors();
  96671. };
  96672. /**
  96673. * Compute the highlights and shadow colors according to their chosen levels.
  96674. */
  96675. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96676. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96677. return;
  96678. }
  96679. // Find the highlight color based on the configuration.
  96680. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96681. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96682. // Find the shadow color based on the configuration.
  96683. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96684. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96685. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96686. };
  96687. /**
  96688. * Build the uniform buffer used in the material.
  96689. */
  96690. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96691. // Order is important !
  96692. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96693. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96694. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96695. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96696. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96697. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96698. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96699. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96700. this._uniformBuffer.addUniform("pointSize", 1);
  96701. this._uniformBuffer.addUniform("shadowLevel", 1);
  96702. this._uniformBuffer.addUniform("alpha", 1);
  96703. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96704. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96705. this._uniformBuffer.create();
  96706. };
  96707. /**
  96708. * Unbind the material.
  96709. */
  96710. BackgroundMaterial.prototype.unbind = function () {
  96711. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96712. this._uniformBuffer.setTexture("diffuseSampler", null);
  96713. }
  96714. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96715. this._uniformBuffer.setTexture("reflectionSampler", null);
  96716. }
  96717. _super.prototype.unbind.call(this);
  96718. };
  96719. /**
  96720. * Bind only the world matrix to the material.
  96721. * @param world The world matrix to bind.
  96722. */
  96723. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96724. this._activeEffect.setMatrix("world", world);
  96725. };
  96726. /**
  96727. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96728. * @param world The world matrix to bind.
  96729. * @param subMesh The submesh to bind for.
  96730. */
  96731. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96732. var scene = this.getScene();
  96733. var defines = subMesh._materialDefines;
  96734. if (!defines) {
  96735. return;
  96736. }
  96737. var effect = subMesh.effect;
  96738. if (!effect) {
  96739. return;
  96740. }
  96741. this._activeEffect = effect;
  96742. // Matrices
  96743. this.bindOnlyWorldMatrix(world);
  96744. // Bones
  96745. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96746. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96747. if (mustRebind) {
  96748. this._uniformBuffer.bindToEffect(effect, "Material");
  96749. this.bindViewProjection(effect);
  96750. var reflectionTexture = this._reflectionTexture;
  96751. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96752. // Texture uniforms
  96753. if (scene.texturesEnabled) {
  96754. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96755. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96756. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96757. }
  96758. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96759. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96760. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96761. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96762. }
  96763. }
  96764. if (this.shadowLevel > 0) {
  96765. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96766. }
  96767. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96768. // Point size
  96769. if (this.pointsCloud) {
  96770. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96771. }
  96772. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96773. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96774. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96775. }
  96776. else {
  96777. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96778. }
  96779. }
  96780. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96781. // Textures
  96782. if (scene.texturesEnabled) {
  96783. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96784. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96785. }
  96786. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96787. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96788. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96789. }
  96790. else if (!defines.REFLECTIONBLUR) {
  96791. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96792. }
  96793. else {
  96794. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96795. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96796. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96797. }
  96798. if (defines.REFLECTIONFRESNEL) {
  96799. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96800. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96801. }
  96802. }
  96803. }
  96804. // Clip plane
  96805. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96806. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96807. }
  96808. if (mustRebind || !this.isFrozen) {
  96809. if (scene.lightsEnabled) {
  96810. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96811. }
  96812. // View
  96813. this.bindView(effect);
  96814. // Fog
  96815. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96816. // image processing
  96817. this._imageProcessingConfiguration.bind(this._activeEffect);
  96818. }
  96819. this._uniformBuffer.update();
  96820. this._afterBind(mesh);
  96821. };
  96822. /**
  96823. * Dispose the material.
  96824. * @param forceDisposeEffect Force disposal of the associated effect.
  96825. * @param forceDisposeTextures Force disposal of the associated textures.
  96826. */
  96827. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96828. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96829. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96830. if (forceDisposeTextures) {
  96831. if (this.diffuseTexture) {
  96832. this.diffuseTexture.dispose();
  96833. }
  96834. if (this.reflectionTexture) {
  96835. this.reflectionTexture.dispose();
  96836. }
  96837. }
  96838. this._renderTargets.dispose();
  96839. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96840. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96841. }
  96842. _super.prototype.dispose.call(this, forceDisposeEffect);
  96843. };
  96844. /**
  96845. * Clones the material.
  96846. * @param name The cloned name.
  96847. * @returns The cloned material.
  96848. */
  96849. BackgroundMaterial.prototype.clone = function (name) {
  96850. var _this = this;
  96851. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96852. };
  96853. /**
  96854. * Serializes the current material to its JSON representation.
  96855. * @returns The JSON representation.
  96856. */
  96857. BackgroundMaterial.prototype.serialize = function () {
  96858. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96859. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96860. return serializationObject;
  96861. };
  96862. /**
  96863. * Gets the class name of the material
  96864. * @returns "BackgroundMaterial"
  96865. */
  96866. BackgroundMaterial.prototype.getClassName = function () {
  96867. return "BackgroundMaterial";
  96868. };
  96869. /**
  96870. * Parse a JSON input to create back a background material.
  96871. * @param source The JSON data to parse
  96872. * @param scene The scene to create the parsed material in
  96873. * @param rootUrl The root url of the assets the material depends upon
  96874. * @returns the instantiated BackgroundMaterial.
  96875. */
  96876. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96877. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96878. };
  96879. /**
  96880. * Standard reflectance value at parallel view angle.
  96881. */
  96882. BackgroundMaterial.StandardReflectance0 = 0.05;
  96883. /**
  96884. * Standard reflectance value at grazing angle.
  96885. */
  96886. BackgroundMaterial.StandardReflectance90 = 0.5;
  96887. __decorate([
  96888. BABYLON.serializeAsColor3()
  96889. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96890. __decorate([
  96891. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96892. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96893. __decorate([
  96894. BABYLON.serializeAsColor3()
  96895. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96896. __decorate([
  96897. BABYLON.serialize()
  96898. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96899. __decorate([
  96900. BABYLON.serialize()
  96901. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96902. __decorate([
  96903. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96904. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96905. __decorate([
  96906. BABYLON.serializeAsTexture()
  96907. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96908. __decorate([
  96909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96910. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96911. __decorate([
  96912. BABYLON.serialize()
  96913. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96914. __decorate([
  96915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96916. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96917. __decorate([
  96918. BABYLON.serializeAsTexture()
  96919. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96920. __decorate([
  96921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96922. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96923. __decorate([
  96924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96925. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96926. __decorate([
  96927. BABYLON.serialize()
  96928. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96929. __decorate([
  96930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96931. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96932. __decorate([
  96933. BABYLON.serializeAsVector3()
  96934. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96935. __decorate([
  96936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96937. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96938. __decorate([
  96939. BABYLON.serialize()
  96940. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96941. __decorate([
  96942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96943. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96944. __decorate([
  96945. BABYLON.serialize()
  96946. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96947. __decorate([
  96948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96949. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96950. __decorate([
  96951. BABYLON.serialize()
  96952. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96953. __decorate([
  96954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96955. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96956. __decorate([
  96957. BABYLON.serialize()
  96958. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96959. __decorate([
  96960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96961. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96962. __decorate([
  96963. BABYLON.serialize()
  96964. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96965. __decorate([
  96966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96967. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96968. __decorate([
  96969. BABYLON.serialize()
  96970. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96971. __decorate([
  96972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96973. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96974. __decorate([
  96975. BABYLON.serialize()
  96976. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96977. __decorate([
  96978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96979. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96980. __decorate([
  96981. BABYLON.serialize()
  96982. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96983. __decorate([
  96984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96985. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96986. __decorate([
  96987. BABYLON.serialize()
  96988. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96989. __decorate([
  96990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96991. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96992. __decorate([
  96993. BABYLON.serializeAsImageProcessingConfiguration()
  96994. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96995. return BackgroundMaterial;
  96996. }(BABYLON.PushMaterial));
  96997. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96998. })(BABYLON || (BABYLON = {}));
  96999. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97000. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97001. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97002. s = arguments[i];
  97003. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97004. t[p] = s[p];
  97005. }
  97006. return t;
  97007. };
  97008. var BABYLON;
  97009. (function (BABYLON) {
  97010. /**
  97011. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97012. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97013. * It also helps with the default setup of your imageProcessing configuration.
  97014. */
  97015. var EnvironmentHelper = /** @class */ (function () {
  97016. /**
  97017. * constructor
  97018. * @param options
  97019. * @param scene The scene to add the material to
  97020. */
  97021. function EnvironmentHelper(options, scene) {
  97022. var _this = this;
  97023. this._errorHandler = function (message, exception) {
  97024. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97025. };
  97026. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97027. this._scene = scene;
  97028. this.onErrorObservable = new BABYLON.Observable();
  97029. this._setupBackground();
  97030. this._setupImageProcessing();
  97031. }
  97032. /**
  97033. * Creates the default options for the helper.
  97034. */
  97035. EnvironmentHelper._getDefaultOptions = function () {
  97036. return {
  97037. createGround: true,
  97038. groundSize: 15,
  97039. groundTexture: this._groundTextureCDNUrl,
  97040. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97041. groundOpacity: 0.9,
  97042. enableGroundShadow: true,
  97043. groundShadowLevel: 0.5,
  97044. enableGroundMirror: false,
  97045. groundMirrorSizeRatio: 0.3,
  97046. groundMirrorBlurKernel: 64,
  97047. groundMirrorAmount: 1,
  97048. groundMirrorFresnelWeight: 1,
  97049. groundMirrorFallOffDistance: 0,
  97050. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97051. groundYBias: 0.00001,
  97052. createSkybox: true,
  97053. skyboxSize: 20,
  97054. skyboxTexture: this._skyboxTextureCDNUrl,
  97055. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97056. backgroundYRotation: 0,
  97057. sizeAuto: true,
  97058. rootPosition: BABYLON.Vector3.Zero(),
  97059. setupImageProcessing: true,
  97060. environmentTexture: this._environmentTextureCDNUrl,
  97061. cameraExposure: 0.8,
  97062. cameraContrast: 1.2,
  97063. toneMappingEnabled: true,
  97064. };
  97065. };
  97066. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97067. /**
  97068. * Gets the root mesh created by the helper.
  97069. */
  97070. get: function () {
  97071. return this._rootMesh;
  97072. },
  97073. enumerable: true,
  97074. configurable: true
  97075. });
  97076. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97077. /**
  97078. * Gets the skybox created by the helper.
  97079. */
  97080. get: function () {
  97081. return this._skybox;
  97082. },
  97083. enumerable: true,
  97084. configurable: true
  97085. });
  97086. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97087. /**
  97088. * Gets the skybox texture created by the helper.
  97089. */
  97090. get: function () {
  97091. return this._skyboxTexture;
  97092. },
  97093. enumerable: true,
  97094. configurable: true
  97095. });
  97096. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97097. /**
  97098. * Gets the skybox material created by the helper.
  97099. */
  97100. get: function () {
  97101. return this._skyboxMaterial;
  97102. },
  97103. enumerable: true,
  97104. configurable: true
  97105. });
  97106. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97107. /**
  97108. * Gets the ground mesh created by the helper.
  97109. */
  97110. get: function () {
  97111. return this._ground;
  97112. },
  97113. enumerable: true,
  97114. configurable: true
  97115. });
  97116. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97117. /**
  97118. * Gets the ground texture created by the helper.
  97119. */
  97120. get: function () {
  97121. return this._groundTexture;
  97122. },
  97123. enumerable: true,
  97124. configurable: true
  97125. });
  97126. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97127. /**
  97128. * Gets the ground mirror created by the helper.
  97129. */
  97130. get: function () {
  97131. return this._groundMirror;
  97132. },
  97133. enumerable: true,
  97134. configurable: true
  97135. });
  97136. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97137. /**
  97138. * Gets the ground mirror render list to helps pushing the meshes
  97139. * you wish in the ground reflection.
  97140. */
  97141. get: function () {
  97142. if (this._groundMirror) {
  97143. return this._groundMirror.renderList;
  97144. }
  97145. return null;
  97146. },
  97147. enumerable: true,
  97148. configurable: true
  97149. });
  97150. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97151. /**
  97152. * Gets the ground material created by the helper.
  97153. */
  97154. get: function () {
  97155. return this._groundMaterial;
  97156. },
  97157. enumerable: true,
  97158. configurable: true
  97159. });
  97160. /**
  97161. * Updates the background according to the new options
  97162. * @param options
  97163. */
  97164. EnvironmentHelper.prototype.updateOptions = function (options) {
  97165. var newOptions = __assign({}, this._options, options);
  97166. if (this._ground && !newOptions.createGround) {
  97167. this._ground.dispose();
  97168. this._ground = null;
  97169. }
  97170. if (this._groundMaterial && !newOptions.createGround) {
  97171. this._groundMaterial.dispose();
  97172. this._groundMaterial = null;
  97173. }
  97174. if (this._groundTexture) {
  97175. if (this._options.groundTexture != newOptions.groundTexture) {
  97176. this._groundTexture.dispose();
  97177. this._groundTexture = null;
  97178. }
  97179. }
  97180. if (this._skybox && !newOptions.createSkybox) {
  97181. this._skybox.dispose();
  97182. this._skybox = null;
  97183. }
  97184. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97185. this._skyboxMaterial.dispose();
  97186. this._skyboxMaterial = null;
  97187. }
  97188. if (this._skyboxTexture) {
  97189. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97190. this._skyboxTexture.dispose();
  97191. this._skyboxTexture = null;
  97192. }
  97193. }
  97194. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97195. this._groundMirror.dispose();
  97196. this._groundMirror = null;
  97197. }
  97198. if (this._scene.environmentTexture) {
  97199. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97200. this._scene.environmentTexture.dispose();
  97201. }
  97202. }
  97203. this._options = newOptions;
  97204. this._setupBackground();
  97205. this._setupImageProcessing();
  97206. };
  97207. /**
  97208. * Sets the primary color of all the available elements.
  97209. * @param color the main color to affect to the ground and the background
  97210. */
  97211. EnvironmentHelper.prototype.setMainColor = function (color) {
  97212. if (this.groundMaterial) {
  97213. this.groundMaterial.primaryColor = color;
  97214. }
  97215. if (this.skyboxMaterial) {
  97216. this.skyboxMaterial.primaryColor = color;
  97217. }
  97218. if (this.groundMirror) {
  97219. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97220. }
  97221. };
  97222. /**
  97223. * Setup the image processing according to the specified options.
  97224. */
  97225. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97226. if (this._options.setupImageProcessing) {
  97227. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97228. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97229. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97230. this._setupEnvironmentTexture();
  97231. }
  97232. };
  97233. /**
  97234. * Setup the environment texture according to the specified options.
  97235. */
  97236. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97237. if (this._scene.environmentTexture) {
  97238. return;
  97239. }
  97240. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97241. this._scene.environmentTexture = this._options.environmentTexture;
  97242. return;
  97243. }
  97244. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97245. this._scene.environmentTexture = environmentTexture;
  97246. };
  97247. /**
  97248. * Setup the background according to the specified options.
  97249. */
  97250. EnvironmentHelper.prototype._setupBackground = function () {
  97251. if (!this._rootMesh) {
  97252. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97253. }
  97254. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97255. var sceneSize = this._getSceneSize();
  97256. if (this._options.createGround) {
  97257. this._setupGround(sceneSize);
  97258. this._setupGroundMaterial();
  97259. this._setupGroundDiffuseTexture();
  97260. if (this._options.enableGroundMirror) {
  97261. this._setupGroundMirrorTexture(sceneSize);
  97262. }
  97263. this._setupMirrorInGroundMaterial();
  97264. }
  97265. if (this._options.createSkybox) {
  97266. this._setupSkybox(sceneSize);
  97267. this._setupSkyboxMaterial();
  97268. this._setupSkyboxReflectionTexture();
  97269. }
  97270. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97271. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97272. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97273. };
  97274. /**
  97275. * Get the scene sizes according to the setup.
  97276. */
  97277. EnvironmentHelper.prototype._getSceneSize = function () {
  97278. var _this = this;
  97279. var groundSize = this._options.groundSize;
  97280. var skyboxSize = this._options.skyboxSize;
  97281. var rootPosition = this._options.rootPosition;
  97282. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97283. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97284. }
  97285. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97286. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97287. });
  97288. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97289. if (this._options.sizeAuto) {
  97290. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97291. this._scene.activeCamera.upperRadiusLimit) {
  97292. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97293. skyboxSize = groundSize;
  97294. }
  97295. var sceneDiagonalLenght = sceneDiagonal.length();
  97296. if (sceneDiagonalLenght > groundSize) {
  97297. groundSize = sceneDiagonalLenght * 2;
  97298. skyboxSize = groundSize;
  97299. }
  97300. // 10 % bigger.
  97301. groundSize *= 1.1;
  97302. skyboxSize *= 1.5;
  97303. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97304. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97305. }
  97306. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97307. };
  97308. /**
  97309. * Setup the ground according to the specified options.
  97310. */
  97311. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97312. var _this = this;
  97313. if (!this._ground) {
  97314. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97315. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97316. this._ground.parent = this._rootMesh;
  97317. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97318. }
  97319. this._ground.receiveShadows = this._options.enableGroundShadow;
  97320. };
  97321. /**
  97322. * Setup the ground material according to the specified options.
  97323. */
  97324. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97325. if (!this._groundMaterial) {
  97326. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97327. }
  97328. this._groundMaterial.alpha = this._options.groundOpacity;
  97329. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97330. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97331. this._groundMaterial.primaryColor = this._options.groundColor;
  97332. this._groundMaterial.useRGBColor = false;
  97333. this._groundMaterial.enableNoise = true;
  97334. if (this._ground) {
  97335. this._ground.material = this._groundMaterial;
  97336. }
  97337. };
  97338. /**
  97339. * Setup the ground diffuse texture according to the specified options.
  97340. */
  97341. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97342. if (!this._groundMaterial) {
  97343. return;
  97344. }
  97345. if (this._groundTexture) {
  97346. return;
  97347. }
  97348. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97349. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97350. return;
  97351. }
  97352. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97353. diffuseTexture.gammaSpace = false;
  97354. diffuseTexture.hasAlpha = true;
  97355. this._groundMaterial.diffuseTexture = diffuseTexture;
  97356. };
  97357. /**
  97358. * Setup the ground mirror texture according to the specified options.
  97359. */
  97360. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97361. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97362. if (!this._groundMirror) {
  97363. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97364. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97365. this._groundMirror.anisotropicFilteringLevel = 1;
  97366. this._groundMirror.wrapU = wrapping;
  97367. this._groundMirror.wrapV = wrapping;
  97368. this._groundMirror.gammaSpace = false;
  97369. if (this._groundMirror.renderList) {
  97370. for (var i = 0; i < this._scene.meshes.length; i++) {
  97371. var mesh = this._scene.meshes[i];
  97372. if (mesh !== this._ground &&
  97373. mesh !== this._skybox &&
  97374. mesh !== this._rootMesh) {
  97375. this._groundMirror.renderList.push(mesh);
  97376. }
  97377. }
  97378. }
  97379. }
  97380. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97381. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97382. };
  97383. /**
  97384. * Setup the ground to receive the mirror texture.
  97385. */
  97386. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97387. if (this._groundMaterial) {
  97388. this._groundMaterial.reflectionTexture = this._groundMirror;
  97389. this._groundMaterial.reflectionFresnel = true;
  97390. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97391. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97392. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97393. }
  97394. };
  97395. /**
  97396. * Setup the skybox according to the specified options.
  97397. */
  97398. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97399. var _this = this;
  97400. if (!this._skybox) {
  97401. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97402. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97403. }
  97404. this._skybox.parent = this._rootMesh;
  97405. };
  97406. /**
  97407. * Setup the skybox material according to the specified options.
  97408. */
  97409. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97410. if (!this._skybox) {
  97411. return;
  97412. }
  97413. if (!this._skyboxMaterial) {
  97414. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97415. }
  97416. this._skyboxMaterial.useRGBColor = false;
  97417. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97418. this._skyboxMaterial.enableNoise = true;
  97419. this._skybox.material = this._skyboxMaterial;
  97420. };
  97421. /**
  97422. * Setup the skybox reflection texture according to the specified options.
  97423. */
  97424. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97425. if (!this._skyboxMaterial) {
  97426. return;
  97427. }
  97428. if (this._skyboxTexture) {
  97429. return;
  97430. }
  97431. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97432. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97433. return;
  97434. }
  97435. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97436. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97437. this._skyboxTexture.gammaSpace = false;
  97438. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97439. };
  97440. /**
  97441. * Dispose all the elements created by the Helper.
  97442. */
  97443. EnvironmentHelper.prototype.dispose = function () {
  97444. if (this._groundMaterial) {
  97445. this._groundMaterial.dispose(true, true);
  97446. }
  97447. if (this._skyboxMaterial) {
  97448. this._skyboxMaterial.dispose(true, true);
  97449. }
  97450. this._rootMesh.dispose(false);
  97451. };
  97452. /**
  97453. * Default ground texture URL.
  97454. */
  97455. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97456. /**
  97457. * Default skybox texture URL.
  97458. */
  97459. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97460. /**
  97461. * Default environment texture URL.
  97462. */
  97463. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97464. return EnvironmentHelper;
  97465. }());
  97466. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97467. })(BABYLON || (BABYLON = {}));
  97468. //# sourceMappingURL=babylon.environmentHelper.js.map
  97469. var BABYLON;
  97470. (function (BABYLON) {
  97471. /**
  97472. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97473. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97474. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97475. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97476. */
  97477. var VideoDome = /** @class */ (function (_super) {
  97478. __extends(VideoDome, _super);
  97479. /**
  97480. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97481. * @param name Element's name, child elements will append suffixes for their own names.
  97482. * @param urlsOrVideo
  97483. * @param options An object containing optional or exposed sub element properties:
  97484. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97485. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97486. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97487. * @param options **loop=true** Automatically loop video on end.
  97488. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97489. */
  97490. function VideoDome(name, urlsOrVideo, options, scene) {
  97491. var _this = _super.call(this, name, scene) || this;
  97492. // set defaults and manage values
  97493. name = name || "videoDome";
  97494. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97495. options.clickToPlay = Boolean(options.clickToPlay);
  97496. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97497. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97498. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97499. // create
  97500. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97501. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97502. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97503. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97504. flat: false,
  97505. radius: options.size,
  97506. subdivisions: options.resolution,
  97507. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97508. }, scene);
  97509. // configure material
  97510. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97511. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97512. material.reflectionTexture = _this._videoTexture;
  97513. material.useEquirectangularFOV = true;
  97514. material.fovMultiplier = 1.0;
  97515. // configure mesh
  97516. _this._mesh.material = material;
  97517. _this._mesh.parent = _this;
  97518. // optional configuration
  97519. if (options.clickToPlay) {
  97520. scene.onPointerUp = function () {
  97521. _this._videoTexture.video.play();
  97522. };
  97523. }
  97524. return _this;
  97525. }
  97526. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97527. /**
  97528. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97529. * Also see the options.resolution property.
  97530. */
  97531. get: function () {
  97532. return this._material.fovMultiplier;
  97533. },
  97534. set: function (value) {
  97535. this._material.fovMultiplier = value;
  97536. },
  97537. enumerable: true,
  97538. configurable: true
  97539. });
  97540. /**
  97541. * Releases resources associated with this node.
  97542. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97543. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97544. */
  97545. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97546. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97547. this._videoTexture.dispose();
  97548. this._mesh.dispose();
  97549. this._material.dispose();
  97550. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97551. };
  97552. return VideoDome;
  97553. }(BABYLON.Node));
  97554. BABYLON.VideoDome = VideoDome;
  97555. })(BABYLON || (BABYLON = {}));
  97556. //# sourceMappingURL=babylon.videoDome.js.map
  97557. 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#ifdef ALPHATEST\nuniform float alphaCutOff;\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<alphaCutOff)\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) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\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;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\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;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\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;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\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) || defined(SPECULARAA)\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#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\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#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\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(-viewDirectionW,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","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);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\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;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,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}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \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{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\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\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\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\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\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;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","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\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97558. 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;\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","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,geometricRoughnessFactor,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,geometricRoughnessFactor,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,geometricRoughnessFactor,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,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\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;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \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\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\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;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\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 vPrimaryColorShadow;\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};"};